Springboot 通过Schedule实现定时任务动态读取执行(从数据库读取)(八)

前言:1、利用反射机制实现。

           2、通过实现SchedulingConfigurer来配置定时任务。

           3、此种方式只能实现项目启动时,定时任务执行,不能再项目启动后开启、暂停任务。

效果:

        数据库中配置了2个任务(状态都是开启的,如果不想执行某条任务,可以将状态改为1)

 

表结构:

CREATE TABLE `schedule_setting` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `job_name` varchar(255) DEFAULT NULL,
  `class_name` varchar(255) DEFAULT NULL,
  `method` varchar(255) DEFAULT NULL,
  `cron` varchar(255) DEFAULT NULL,
  `status` int(2) DEFAULT NULL COMMENT '0 代表开启,1代表关闭',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

项目启动后开启执行,数据库中定义的2个方法

代码实现:

任务实体

/**
 * @author : 徐长城
 * @des:
 * @date : 2019/8/20 21:37
 */
public class ScheduleConfig {
    private Long id;

    private String jobName;

    private String className;

    private String method;

    private String cron;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }
}

Dao以及xml

Springboot获取bean

/**
 * @author : 徐长城
 * @des:   获取bean
 * @date : 2019/8/20 21:59
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public ApplicationContextHelper() {
    }

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

    public static Object getBean(String beanName) {
        return applicationContext != null?applicationContext.getBean(beanName):null;
    }
}

定时配置

/**
 * @author : 徐长城
 * @des:
 * @date : 2019/8/20 21:43
 */
@Component
public class ScheduleSetting implements SchedulingConfigurer {

    @Autowired
    private ScheduleDao scheduleDao;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        // 获取所有任务
        List<ScheduleConfig> scheduleList = scheduleDao.getScheduleList();
        System.out.println(scheduleList.size());
         for (ScheduleConfig s : scheduleList){
             scheduledTaskRegistrar.addTriggerTask(getRunnable(s), getTrigger(s));
         }
    }


    /**
     * 转换首字母小写
     *
     * @param str
     * @return
     */
    public static String lowerFirstCapse(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    /**
     * runnable
     * @param scheduleConfig
     * @return
     */
    private Runnable getRunnable(ScheduleConfig scheduleConfig){
        return new Runnable() {
            @Override
            public void run() {
                Class<?> clazz;
                try {
                    clazz = Class.forName(scheduleConfig.getClassName());
                    String className = lowerFirstCapse(clazz.getSimpleName());
                    Object bean = (Object) ApplicationContextHelper.getBean(className);
                    Method method = ReflectionUtils.findMethod(bean.getClass(), scheduleConfig.getMethod());
                    ReflectionUtils.invokeMethod(method, bean);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
    }

    /**
     * Trigger
     * @param scheduleConfig
     * @return
     */
    private Trigger getTrigger(ScheduleConfig scheduleConfig){
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger trigger = new CronTrigger(scheduleConfig.getCron());
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };

    }
}

启动类中添加@EnableScheduling

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值