首页 > 代码库 > Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 任务调度动态改变时间

Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 任务调度动态改变时间

不需要重启应用就可以动态的改变Cron表达式的值

import java.util.Date;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Lazy;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;@Lazy(false)@Component@EnableSchedulingpublic class DynamicScheduledTask implements SchedulingConfigurer {        /**     *  通过自动注入启动任务调度     *       *  @Autowired     *  DynamicScheduledTask dynamicScheduledTask;     *       */    private final Logger logger = LoggerFactory.getLogger(this.getClass());    private static final String DEFAULT_CRON = "0 0/10 * * * ? ";    private String cron = DEFAULT_CRON;        /**     * 获取任务执行规则     * @return     */    public String getCron() {        return cron;    }    /**     * 设置任务执行规则     * @param cron     */    public void setCron(String cron) {        this.cron = cron;    }    @Override    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        taskRegistrar.addTriggerTask(new Runnable() {            @Override            public void run() {                // 任务逻辑                logger.debug("dynamicCronTask is running...");            }        }, new Trigger() {            @Override            public Date nextExecutionTime(TriggerContext triggerContext) {                // 任务触发,可修改任务的执行周期                CronTrigger trigger = new CronTrigger(cron);                Date nextExec = trigger.nextExecutionTime(triggerContext);                return nextExec;            }        });    }}

 

Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 任务调度动态改变时间