Ash*_*shu 6 java spring scheduled-tasks
我正在产生一个线程,它将继续从数据库中提取大量记录并将它们放入队列中.该线程将在服务器负载上启动.我希望这个线程始终处于活动状态.如果数据库中没有记录,我希望它等待一段时间后再次检查.我正在考虑使用spring任务调度程序来安排这个,但不确定这是否正确,因为我只希望我的任务启动一次.在Spring中实现这个的好方法是什么?
此外,我需要进行边界检查,如果我的线程发生故障(由于任何错误或异常情况),它应该在一段时间后重新实例化.
我可以通过使用线程通信方法在java中完成所有这些操作,但只是尝试在Spring或Java中可用于此类场景.
任何建议或指针都会有所帮助.
您可以使用@Scheduled注释来运行作业.首先使用带注释的方法创建一个类@Scheduled.
类
public class GitHubJob {
@Scheduled(fixedDelay = 604800000)
public void perform() {
//do Something
}
}
Run Code Online (Sandbox Code Playgroud)
然后在配置文件中注册此类.
弹簧的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>
Run Code Online (Sandbox Code Playgroud)
有关计划的更多信息,请访问Spring Docs.
小智 0
您可以尝试使用 Quartz 调度程序。http://quartz-scheduler.org/ 这将允许您指定任务执行之间的持续时间。您可以设置一个标志(布尔值)来指示该类之前是否运行过,以避免重复您只想运行“第一次”的代码。
| 归档时间: |
|
| 查看次数: |
12601 次 |
| 最近记录: |