Spring动态配置计时器触发时间的实例代码
Spring中添加计时器的时候根据业务需求可能会需要动态处理触发时间;
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动态配置计时器触发时间的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
赞 (0)