Spring / Java中的调度任务 [英] Scheduling Task in Spring/Java

查看:99
本文介绍了Spring / Java中的调度任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am spawning a thread which will keep pulling the chunk of records from database and putting them into the queue. This thread will be started on the server load. I want this thread to be active all the time. If there are no records in the database I want it to wait and check again after some time. I was thinking of using spring task scheduler to schedule this but not sure if that is right because I only want my task to be started once. What will be the good way of implementing this in Spring ?

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

Also, i need to have a boundary check that if my thread goes down (because of any error or exception condition) it should be re-instantiated after some time.

我可以通过使用线程通信方法在java中完成所有这些,但只是尝试在Spring或Java中有可用的东西对于这种情况。

I can do all this in java by using thread communication methods but just trying if there is something available in Spring or Java for such scenarios.

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

Any suggestions or pointer will help.

推荐答案

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

You can use the @Scheduled annotation to run jobs. First create a class with a method that is annotated with @Scheduled.

public class GitHubJob {

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

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

Then register this class in your configuration files.

spring-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

For more about scheduling visit the Spring Docs.

这篇关于Spring / Java中的调度任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆