天天看点

java定时器Scheduled,可动态设置定时器执行时间

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;
    }
}