栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA-springboot动态添加定时任务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


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

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

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        //获取定时任务执行信息
        List 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 getAllTasks(String id) {
        List  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;
            }
        };
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000400.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号