2013-03-19 62 views
6

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

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

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

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

回答

0

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

0

Spring对调度任务提供了支持。 Here are for the docs为最新的3.2.x版本的春季,但检查您正在使用的版本的文档。看起来它使用Quartz来调度任务。

+0

我已经通过了它,但我不想让我的任务在特定时间后执行,但只有一次。只需要处理一个场景,如果我的任务停止了,我该如何恢复它。 – Ashu 2013-03-20 00:08:01

6

您可以使用@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

0

我认为你的要求只是普通的石英或弹簧调度框架支持很好。但你想创建一个特殊的方法来实现它。我的建议是保持简单和愚蠢。春天的模拟将通过合并来利用你的工作线程,而不是一直运行它。

从统计数据来看,很容易检查工人类的日志。如果您希望在Web控制台中查看统计信息,则需要记录工作人员在数据库中的日志。我相信你可以用普通的方式轻松完成。

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

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