SpringBoot实现数据库配置定时任务

spring-boot 2.0.2.RELEASE,将定时任务配置在数据库,启动项目的时候,用mybatis读取数据库,实例化对象,并设定定时任务。如果需要新增,减少,修改定时任务,仅需要修改数据库资料,并重启项目即可,无需改代码。

完整源代码下载  https://download.csdn.net/download/howard789/10567928

 

package com.example.scheduledTask;

import com.example.mybatis.dao.SysTaskMapper;
import com.example.mybatis.model.SysTask;
import com.example.mybatis.model.SysTaskExample;
import com.example.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
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 javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Lazy(value = false)
@Component
public class SysTaskConfig implements SchedulingConfigurer {

    protected static Logger logger = LoggerFactory.getLogger(SysTaskConfig.class);

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private SysTaskMapper sysTaskMapper;

    //从数据库里取得所有要执行的定时任务
    private List getAllTasks() {
        SysTaskExample example=new SysTaskExample();
        example.createCriteria().andIsDeleteEqualTo((byte) 0);
        return sysTaskMapper.selectByExample(example);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List tasks=getAllTasks();
        logger.info("定时任务启动,预计启动任务数量="+tasks.size()+"; time="+sdf.format(new Date()));

        //校验数据(这个步骤主要是为了打印日志,可以省略)
        checkDataList(tasks);

        //通过校验的数据执行定时任务
        int count = 0;
        if(tasks.size()>0) {
            for (int i = 0; i < tasks.size(); i++) {
                try {
                    taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)), getTrigger(tasks.get(i)));
                    count++;
                } catch (Exception e) {
                    logger.error("定时任务启动错误:" + tasks.get(i).getClassName() + ";" + tasks.get(i).getMethodName() + ";" + e.getMessage());
                }
            }
        }
        logger.info("定时任务实际启动数量="+count+"; time="+sdf.format(new Date()));
    };


    private Runnable getRunnable(SysTask task){
        return new Runnable() {
            @Override
            public void run() {
                try {
                    Object obj = SpringUtil.getBean(task.getClassName());
                    Method method = obj.getClass().getMethod(task.getMethodName(),null);
                    method.invoke(obj);
                } catch (InvocationTargetException e) {
                    logger.error("定时任务启动错误,反射异常:"+task.getClassName()+";"+task.getMethodName()+";"+ e.getMessage());
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        };
    }

    private Trigger getTrigger(SysTask task){
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //将Cron 0/1 * * * * ? 输入取得下一次执行的时间
                CronTrigger trigger = new CronTrigger(task.getCron());
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };

    }

    private List checkDataList(List list) {
        String errMsg="";
        for(int i=0;i

数据库配置

运行的结果

SpringBoot实现数据库配置定时任务_第1张图片

你可能感兴趣的:(java,springboot)