Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 動態改變時間


import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
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;
    }
    
    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(20);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //用於設置定時任務線程數,默認不設置的話為單線程
        taskRegistrar.setScheduler(taskExecutor());
        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;
            }
        });
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM