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;
    }
}
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值