繁体   English   中英

Spring / Java中的调度任务

[英]Scheduling Task in Spring/Java

我正在产生一个线程,它将继续从数据库中提取大量记录并将它们放入队列中。 该线程将在服务器负载上启动。 我希望这个线程始终处于活动状态。 如果数据库中没有记录,我希望它等待一段时间后再次检查。 我正在考虑使用spring任务调度程序来安排这个,但不确定这是否正确,因为我只希望我的任务启动一次。 在Spring中实现这个的好方法是什么?

此外,我需要进行边界检查,如果我的线程发生故障(由于任何错误或异常情况),它应该在一段时间后重新实例化。

我可以通过使用线程通信方法在java中完成所有这些操作,但只是尝试在Spring或Java中可用于此类场景。

任何建议或指针都会有所帮助。

您可以使用@Scheduled批注来运行作业。 首先使用@Scheduled注释的方法创建一个类。

public class GitHubJob {

   @Scheduled(fixedDelay = 604800000)
   public void perform() {
      //do Something
    }
}

然后在配置文件中注册此类。

弹簧的context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<tx:annotation-driven/>
<task:annotation-driven scheduler="myScheduler"/>

<task:scheduler id="myScheduler" pool-size="10"/>
<bean id="gitHubJob" class="org.tothought.spring.jobs.GitHubJob"/>

</beans>

有关计划的更多信息,请访问Spring Docs

@Scheduled(fixedDelay=3600000)
private void refreshValues() {
   [...]
}

每小时运行一次任务。 它必须是无效的并且不接受任何参数。 如果使用Spring的Java配置,则还需要将注释@EnableScheduling添加到@Configuration类之一。

您可以尝试使用Quartz调度程序。 http://quartz-scheduler.org/这将允许您指定任务执行之间的持续时间。 您可以设置一个标志(布尔值),表示该类之前是否已运行,以避免重复您只想运行“第一次”的代码。

Spring为调度任务提供了开箱即用的支持。 这里是最新3.2.x版本spring的文档,但请查看您正在使用的版本的文档。 看起来它在引擎盖下使用Quartz来安排任务。

我认为你的要求只是常规的senario石英或弹簧调度框架非常好。 但你想创造一种特殊的方法来实现它。 我的建议是保持简单和愚蠢。 spring scheudling将通过池化来利用您的工作线程,而不是一直运行它。

从统计数据来看,检查工人类的日志很容易。 如果要在Web控制台中查看统计信息,则需要记录worker的登录数据库。 我相信你能以正常方式轻松搞定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM