JAVA-springboot动态添加定时任务

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (SchedulerTask)数据同步
 *0/10 * * * * ?
 */
@Component
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
public class SchedulerTask implements SchedulingConfigurer {
    @Mapper
    public interface CronMapper {
        @Select("select * from access_work_shift_time")
        List<AccessWorkShiftTimeVO> getCron();
    }

    @Autowired
    @SuppressWarnings("all")
    CronMapper cronMapper;
    //记录日志
    private Logger logger = LoggerFactory.getLogger(SchedulerTask.class);

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        //获取定时任务执行信息
        List<AccessWorkShiftTimeVO> tasks = getAllTasks(null);
        if (tasks.size() > 0) {
            for (int i = 0; i < tasks.size(); i++) {
                try {
                    // 注册计时任务到Scheduling接口
                    taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)), getTrigger(tasks.get(i)));
                } catch (Exception e) {
                    logger.error("定时任务启动错误:" + e.getMessage());
                }
            }
        }
    }

    
    //从数据库里取得所有要执行的定时任务
    private List<AccessWorkShiftTimeVO> getAllTasks(String id) {
        List<AccessWorkShiftTimeVO>  list = new ArrayList<>();
        try {
            list=cronMapper.CronMapper();
        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
        }
        return list;
    }

    //执行业务逻辑
    private Runnable getRunnable(AccessWorkShiftTimeVO SchedulerConfig) {
        return new Runnable() {
            @Override
            public void run() {
               //业务代码
            }
        };
    }

    //获取下次执行时间
    public Trigger getTrigger(AccessWorkShiftTimeVO  schedulerConfig) {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                AccessWorkShiftTimeVO cpSyncCron = new AccessWorkShiftTimeVO();
				cpSyncCron = getAllTasks(schedulerConfig.getId()).get(0);
                String cron = "";
                if (cpSyncCron != null) {
                    cron = cpSyncCron.getCron();
                }
                if (cron == null || "".equals(cron)) {
                    return null;
                }
                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExec = cronTrigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值