Spring中添加计时器的时候根据业务需求可能会需要动态处理触发时间;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import java.util.Date; @Component @EnableScheduling public class SchedulerTest implements SchedulingConfigurer { private final static Logger logger = LoggerFactory.getLogger(SchedulerTest. class ); public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { // 注册计时任务到Scheduling接口 scheduledTaskRegistrar.addTriggerTask( new Runnable() { public void run() { logger.info( "task job is running..." ); } }, new Trigger() { public Date nextExecutionTime(TriggerContext triggerContext) { CronTrigger cronTrigger = new CronTrigger( "时间表达式" ); Date nextExec = cronTrigger.nextExecutionTime(triggerContext); return nextExec; } }); } } |
PS:多个计时任务添加的时候只用都注册到Spring中即可
总结
以上所述是小编给大家介绍的Spring动态配置计时器触发时间的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/u012680274/article/details/80591883