码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-26 13:49:18      阅读:4036      评论:0      收藏:0      [点我收藏+]

标签:config   running   conf   rar   spring   enables   需要   ota   任务调度   

不需要重启应用就可以动态的改变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
@EnableScheduling
public 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 * * * ? ") 任务调度动态改变时间

标签:config   running   conf   rar   spring   enables   需要   ota   任务调度   

原文地址:http://www.cnblogs.com/rinack/p/6768136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!