前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot动态配置定时任务cron(动态改变执行周期)

SpringBoot动态配置定时任务cron(动态改变执行周期)

作者头像
JQ实验室
发布2022-02-10 14:37:52
1.6K0
发布2022-02-10 14:37:52
举报
文章被收录于专栏:实用技术
代码语言:javascript
复制
package model;

public class SpringScheduledCron {
    private String cronId;
    private String cronKey;
    private String cronExpression;
    private String taskExplain;
    private String status;

    
    
    @Override
    public String toString() {
        return "SpringScheduledCron{" + "cronId=" + cronId + ", cronKey='" + cronKey + '\'' + ", cronExpression='"
                + cronExpression + '\'' + ", taskExplain='" + taskExplain + '\'' + ", status=" + status + '}';
    }

    public String getCronId() {
        return cronId;
    }

    public void setCronId(String cronId) {
        this.cronId = cronId;
    }

    public String getCronKey() {
        return cronKey;
    }

    public void setCronKey(String cronKey) {
        this.cronKey = cronKey;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public String getTaskExplain() {
        return taskExplain;
    }

    public void setTaskExplain(String taskExplain) {
        this.taskExplain = taskExplain;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    
    
    public SpringScheduledCron() {
        // TODO Auto-generated constructor stub
    }

    public SpringScheduledCron(String cronId, String cronKey, String cronExpression, String taskExplain,
            String status) {
        this.cronId = cronId;
        this.cronKey = cronKey;
        this.cronExpression = cronExpression;
        this.taskExplain = taskExplain;
        this.status = status;
    }
    
    
    
}
代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;


@Component
public class SpringScheduledCronRepository {

    static int i = 0;
    static {
        System.out.println("in=="+(i++));
    }
    
    public SpringScheduledCron findByCronKey(String cronKey) {
        
        SpringScheduledCron cron = null;
        
        List<SpringScheduledCron> list = findAll();
        for (SpringScheduledCron springScheduledCron : list) {
            if(springScheduledCron.getCronKey().equals(cronKey)) {
                cron = springScheduledCron;
            }
        }
        
        return cron;
    };

    public List<SpringScheduledCron> findAll(){
        
        List<SpringScheduledCron> list = new ArrayList<SpringScheduledCron>();
        try {
            
            File cronFile = new File("./config/cron.txt");
            FileReader in = new FileReader(cronFile);
            BufferedReader bufIn = new BufferedReader(in);
            // 替换
            String line = null;
            while ((line = bufIn.readLine()) != null) {
                String[] ls = line.split("\\|");
                if(ls.length == 5) {
                    SpringScheduledCron cron =  new SpringScheduledCron(ls[0],ls[1],ls[2],ls[3],ls[4]);
                    list.add(cron);
                }
            }
            // 关闭 输入流
            bufIn.close();
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }
        return list;
    };

}
代码语言:javascript
复制
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.context = applicationContext;
    }

    public static <T> T getBean(Class<T> clz) {
        return context.getBean(clz);
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public ApplicationContext getApplicationContext() {
        return context;
    }

}
代码语言:javascript
复制
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;

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

@Configuration
public class ScheduledConfig implements SchedulingConfigurer {

    @Autowired
    private ApplicationContext context;
    
    @Autowired
    private SpringScheduledCronRepository cronRepository;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        for (SpringScheduledCron springScheduledCron : cronRepository.findAll()) {
            Class<?> clazz;
            Object task;
            try {
                clazz = Class.forName(springScheduledCron.getCronKey());
                task = context.getBean(clazz);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("" + springScheduledCron.getCronKey() + "有误", e);
            } catch (BeansException e) {
                throw new IllegalArgumentException(springScheduledCron.getCronKey() + "未纳入到spring管理", e);
            }
            Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
            // 可以通过改变数据进而实现动态改变执行周期
            taskRegistrar.addTriggerTask(((Runnable) task),
                    triggerContext -> {
                        String cronExpression = cronRepository.findByCronKey(springScheduledCron.getCronKey()).getCronExpression();
                        return new CronTrigger(cronExpression).nextExecutionTime(triggerContext);
                    }
            );
        }

    }

    @Bean
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }

}
代码语言:javascript
复制
public interface ScheduledOfTask extends Runnable {
    /**
     * 定时任务方法
     */
    void execute();
    /**
     * 实现控制定时任务启用或禁用的功能
     */
    @Override
    default void run() {
        SpringScheduledCronRepository repository = SpringUtils.getBean(SpringScheduledCronRepository.class);
        SpringScheduledCron scheduledCron = repository.findByCronKey(this.getClass().getName());
        if ("".equals(scheduledCron.getStatus())) {
            return;
        }
        execute();
    }
}


@Component
public class DynamicPrintTask implements ScheduledOfTask {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private int i;

    @Override
    public void execute() {
        logger.info("thread id:{},DynamicPrintTask execute times:{}", Thread.currentThread().getId(), ++i);
    }

}
代码语言:javascript
复制
1|com.schedule.DynamicPrintTask|*/10 * * * * ?|5s执行一次|1
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档