SpringBoot 整合 Quartz 實現依賴數據庫數據動態設置定時任務

簡單的定時任務用 spring的 @Scheduled 註解便可

@Component
public class ScheduledTask {
    
    @Scheduled(fixedRate = 5000)
    //表示每隔5000ms,Spring scheduling會調用一次該方法,不論該方法的執行時間是多少
    public void reportCurrentTime() throws InterruptedException {
        System.out.println(new Date()));
    }

    @Scheduled(fixedDelay = 5000)
    //表示當方法執行完畢5000ms後,Spring scheduling會再次調用該方法
    public void reportCurrentTimeAfterSleep() throws InterruptedException {
        System.out.println(new Date()));
    }

    @Scheduled(cron = "0 0 1 * * *")
    //提供了一種通用的定時任務表達式,這裏表示每隔5秒執行一次,更加詳細的信息能夠參考cron表達式。
    public void reportCurrentTimeCron() throws InterruptedException {
        System.out.println(new Date()));
    }
}
複製代碼
  • 運行類
@SpringBootApplication
@EnableScheduling
//告訴Spring建立一個task executor,若是咱們沒有這個標註,全部@Scheduled標註都不會執行
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

複製代碼

Quartz 實現動態設置定時任務

  • 官網:http://www.quartz-scheduler.org/
  • 實戰

首先須要一個配置類java

package com.*.myquartz;
import org.quartz.Scheduler;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @Author by xup .
 * @Descriptions
 * @Datetime in 2018/1/30 17:07.
 */
@Configuration
public class QuartzConfiguration {
    //解決Job中注入Spring Bean爲null的問題
    @Component("quartzJobFactory")
    private class QuartzJobFactory extends AdaptableJobFactory {
        //這個對象Spring會幫咱們自動注入進來,也屬於Spring技術範疇.
        @Autowired
        private AutowireCapableBeanFactory capableBeanFactory;

        protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
            //調用父類的方法
            Object jobInstance = super.createJobInstance(bundle);
            //進行注入,這屬於Spring的技術,不清楚的能夠查看Spring的API.
            capableBeanFactory.autowireBean(jobInstance);
            return jobInstance;
        }
    }
    //注入scheduler到spring,在下面quartzManege會用到
    @Bean(name = "scheduler")
    public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception {

        SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
        factoryBean.setJobFactory(quartzJobFactory);
        factoryBean.afterPropertiesSet();
        Scheduler scheduler=factoryBean.getScheduler();
        scheduler.start();
        return scheduler;
    }
}

複製代碼

還須要quartz 用到的實體類spring

package com.*.myquartz;
import lombok.Data;

/**
  * @author xup
  * @since 2018-01-29
 */
@Data
public class QuartzJob {

	public static final Integer STATUS_RUNNING = 1;
	public static final Integer STATUS_NOT_RUNNING = 0;
	public static final Integer CONCURRENT_IS = 1;
	public static final Integer CONCURRENT_NOT = 0;

	private String jobId;
        /**
         * cron 表達式
         */
	private String cronExpression;
        /**
         * 任務調用的方法名
         */
	private String methodName;
        /**
         * 任務是否有狀態
         */
	private Integer isConcurrent;
        /**
         * 描述
         */
	private String description;
        /**
         * 任務執行時調用哪一個類的方法 包名+類名,徹底限定名
         */
	private String beanName;
    	/**
         * 觸發器名稱
         */
	private String triggerName;

        /**
         * 任務狀態
         */
	private Integer jobStatus;
	private String springBean;
        /**
         * 任務名
         */
	private String jobName;

}

複製代碼

接着是任務管理類數據庫

根據傳入quartzJob 類參數決定調用那個類的定時任務方法 與上面介紹的簡單schedule更靈活。可實現不修改配置文件來開啓和停用定時任務,無需重啓項目apache

package com.*.myquartz;
import org.quartz.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @Author by xup .
 * @Descriptions
 * @Datetime in 2018/1/30 17:20.
 */
@Component
public class QuartzManage {

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    public void addJob(QuartzJob job) throws SchedulerException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        //經過類名獲取實體類,即要執行的定時任務的類
        Class<?> clazz = Class.forName(job.getBeanName());
        Job jobEntity = (Job)clazz.newInstance();
        //經過實體類和任務名建立 JobDetail
        JobDetail jobDetail = newJob(jobEntity.getClass())
                .withIdentity(job.getJobName()).build();
        //經過觸發器名和cron 表達式建立 Trigger
        Trigger cronTrigger = newTrigger()
                .withIdentity(job.getTriggerName())
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression()))
                .build();
        //執行定時任務
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }

    /**
     * 更新job cron表達式
     * @param quartzJob
     * @throws SchedulerException
     */
    public void updateJobCron(QuartzJob quartzJob) throws SchedulerException {

        TriggerKey triggerKey = TriggerKey.triggerKey(quartzJob.getJobName());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey, trigger);
    }
    /**
     * 刪除一個job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void deleteJob(QuartzJob quartzJob) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
        scheduler.deleteJob(jobKey);
    }
    /**
     * 恢復一個job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void resumeJob(QuartzJob quartzJob) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
        scheduler.resumeJob(jobKey);
    }
    /**
     * 當即執行job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void runAJobNow(QuartzJob quartzJob) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
        scheduler.triggerJob(jobKey);
    }
    /**
     * 暫停一個job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void pauseJob(QuartzJob quartzJob) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
        scheduler.pauseJob(jobKey);
    }
}

複製代碼

最後是測試類bash

注意:定時任務必須實現Job接口, 而後將定時任務的方法放入execute()方法中便可app

package com.*.myquartz;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;

@Slf4j
public class TaskTest implements Job {

	public void run() {
	    for (int i = 0; i < 10; i++) {
    		log.info(i+" run ################## " + (new Date()));
    	    }
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
	    run();
	}
}

複製代碼

後臺管理界面,可隨時開啓,停用定時任務ide

接入業務邏輯實現數據庫同步

這裏的實體類(針對數據庫)和quartz中的實體類(針對quartz)須要作一下轉換,固然他們的字段能夠徹底一致測試

@Autowired
    private QuartzManage quartzManage;

    @Autowired
    private ScheduleJobDao scheduleJobDao;
    
    //這裏添加定時任務時,默認是不開啓的,須要手動執行開啓,暫停任務
    @Override
    public ResultData<Boolean> addScheduleJob(ScheduleJobForm scheduleJobForm) {
        if (!CronExpression.isValidExpression(scheduleJobForm.getCronExpression())){
            return new ResultData<>(ResultMsg.ERROR,"cron表達式格式錯誤!");
        }
        return new ResultData<>(add(scheduleJobForm));
    }

    //開啓或暫停定時任務
    @Override
    public boolean changeJobStatus(ScheduleJobForm scheduleJobForm) throws SchedulerException, IllegalAccessException, InstantiationException, ClassNotFoundException {
        ScheduleJobForm oldJob = scheduleJobDao.selectById(scheduleJobForm.getJobId());
        oldJob.setJobStatus(scheduleJobForm.getJobStatus());
        if (XpObjectUtil.equals(scheduleJobForm.getJobStatus(), QuartzJob.STATUS_RUNNING)){
            quartzManage.addJob(QuartzJobUtils.entityToData(oldJob));
        } else if (XpObjectUtil.equals(scheduleJobForm.getJobStatus(), QuartzJob.STATUS_NOT_RUNNING)) {
            quartzManage.deleteJob(QuartzJobUtils.entityToData(oldJob));
        }
        scheduleJobForm.setUpdateBy(SecurityUtil.getCurrUserAccount());
        return editById(scheduleJobForm);
    }

複製代碼
  • 這裏還有個問題,項目重啓時全部運行的定時任務會被銷燬

下面的操做即爲項目啓動時從新載入啓用狀態的定時任務ui

這時實現 ApplicationRunner接口 重寫run方法便可 項目啓動時會執行run方法裏的操做spa

package com.*.myquartz;
import com.*.enums.DataStatus;
import com.*.task.schedule.form.ScheduleJobForm;
import com.*.task.schedule.service.ScheduleJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author by xup .
 * @Descriptions
 * @Datetime in 2018/1/31 11:41.
 */

@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {
    @Autowired
    private ScheduleJobService scheduleJobService;

    @Override
    //項目啓動時從新激活啓用的定時任務
    public void run(ApplicationArguments applicationArguments) throws Exception {
        ScheduleJobForm scheduleJobForm = new ScheduleJobForm();
        scheduleJobForm.setDeleteFlag(DataStatus.DEFAULT.getStatus());
        scheduleJobForm.setJobStatus(1);
        List<ScheduleJobForm> scheduleJobList = scheduleJobService.selectList(scheduleJobForm);
        log.info("##########################"+scheduleJobList.size());
        if (CollectionUtils.isNotEmpty(scheduleJobList)){
            scheduleJobService.initScheduleJob(scheduleJobList);
        }
    }
}

複製代碼

到此一個完整的定時任務管理模塊完成了

相關文章
相關標籤/搜索