zoukankan      html  css  js  c++  java
  • 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;
                }
            });
        }
    }
  • 相关阅读:
    Web上传大文件的解决方案
    JS上传大文件的解决方案
    网页上传大文件的解决方案
    B/S上传大文件的解决方案
    Unity UGUI——提供可视功能的UI组件(Text)
    Java设计模式透析之 —— 策略(Strategy)
    【边做项目边学Android】小白会遇到的问题--Appcompat_V7问题
    高度平衡树 -- AVL 树
    成长这事儿,不可不说-------Day36
    Cocos2D-X2.2.3学习笔记5(UI系统)
  • 原文地址:https://www.cnblogs.com/XJJD/p/9952893.html
Copyright © 2011-2022 走看看