概述
java定时器任务,可动态设置定时器执行时间,无延时
@Component
@EnableScheduling
public class DayTimerTask implements SchedulingConfigurer {
private final static Logger logger = LoggerFactory.getLogger(DayTimerTask.class);
//动态设置定时器执行时间
@Autowired
private TimerConfigureService timerConfigureService;
private static String cron;
private static ScheduledTaskRegistrar scheduledtaskRegistrar;
private static ScheduledFuture<?> future;
public DayTimerTask() {
cron = "0 50 23 * * ?";
}
/**
* 轮询查询日期设置 30分钟
*/
@Scheduled(cron = "0 0/30 * * * ?")
public void test(){
//查询动态设置的定时器执行时间
TimerConfigure timerConfigure = timerConfigureService.getOne(
Wrappers.<TimerConfigure>lambdaQuery()
.eq(TimerConfigure::getType, 0));
if(!cron.equals(timerConfigure.getCron())){
if(Objects.nonNull(future)){
future.cancel(true);
}
timer(timerConfigure.getCron());
}else {
if(Objects.isNull(future)){
timer(cron);
}
}
//修改每天更新时间
cron = timerConfigure.getCron();
}
public void timer(String nextCron){
TaskScheduler scheduler = scheduledtaskRegistrar.getScheduler();
Runnable runnable = () -> {
// 任务逻辑
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info("开始执行定时任务(每天),开始时间:" + sf.format(new Date()));
//执行具体的业务
logger.info("定时任务执行完成(每天),更新完成时间:" + sf.format(new Date()));
};
Trigger trigger = triggerContext -> {
// 任务触发,可修改任务的执行周期
CronTrigger trigger1 = new CronTrigger(nextCron);
Date nextExec = trigger1.nextExecutionTime(triggerContext);
return nextExec;
};
future = scheduler.schedule(runnable, trigger);
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
scheduledtaskRegistrar = taskRegistrar;
}
}
最后
以上就是故意中心为你收集整理的java定时器Scheduled,可动态设置定时器执行时间的全部内容,希望文章能够帮你解决java定时器Scheduled,可动态设置定时器执行时间所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复