spring boot 动态改变定时时间

package com.rkt.demo.Task;

import com.rkt.demo.dao.MyDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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 java.util.Date;

@Configuration      
@EnableScheduling
public class SchTask implements SchedulingConfigurer {
    private static String CRON = "0 57 14 * * ?";
    @Autowired
    private MyDao userDao;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new initTask(), new CronTask());
    }

    private class CronTask implements Trigger {
        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            System.out.println("查询库:" + userDao.selectUserByUserName("xxx"));
            CronTrigger trigger = new CronTrigger(CRON);
            return trigger.nextExecutionTime(triggerContext);
        }
    }

    private class initTask implements Runnable {
        @Override
        public void run() {
            System.out.println("定时开始---");
        }
    }

}

网上有有lambda写的版本

你可能感兴趣的:(spring boot 动态改变定时时间)