1. 程式人生 > >springmvc 動態 新增/修改 定時任務

springmvc 動態 新增/修改 定時任務

springmvc  +  quartz 動態定時任務

1、jar 包

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.1.1</version>
    <exclusions>
        <exclusion>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
        </exclusion>
    </exclusions>
</dependency>
spring版本  
4.3.4.RELEASE

2、xml 配置檔案

    <bean id="jobFactory" class="xxx.MyJobFactory"/>

    <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobFactory" ref="jobFactory"></property>
    </bean>

3、xml 對應java 類

xxx.MyJobFactory java類
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

@Component
public class MyJobFactory extends AdaptableJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 呼叫父類的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 進行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

4、java 實現類 

QuartzManager.java  實現動態新增定時任務的型別
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuartzManager {


    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    @Autowired
    private MyJobFactory myJobFactory;


    /**
     * @Description: 新增一個定時任務
     *
     * @param jobName 任務名
     * @param jobGroupName  任務組名
     * @param triggerName 觸發器名
     * @param triggerGroupName 觸發器組名
     * @param jobClass  任務
     * @param cron   時間設定,參考quartz說明文件
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public  void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class jobClass, String cron,JobDataMap jobDataMap) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            sched.setJobFactory(myJobFactory);

            // 任務名,任務組,任務執行類
            JobDetail jobDetail= JobBuilder.newJob(jobClass).usingJobData(jobDataMap).withIdentity(jobName, jobGroupName).build();

            // 觸發器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 觸發器名,觸發器組
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 觸發器時間設定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 建立Trigger物件
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();


            // 排程容器設定JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);

            // 啟動
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一個任務的觸發時間
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName 觸發器名
     * @param triggerGroupName 觸發器組名
     * @param cron   時間設定,參考quartz說明文件
     */
    public  void modifyJobTime(String jobName,
                                     String jobGroupName, String triggerName, String triggerGroupName, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            //sched.setJobFactory(myJobFactory);
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /** 方式一 :呼叫 rescheduleJob 開始 */
                // 觸發器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 觸發器名,觸發器組
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 觸發器時間設定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 建立Trigger物件
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 :修改一個任務的觸發時間
                sched.rescheduleJob(triggerKey, trigger);
                /** 方式一 :呼叫 rescheduleJob 結束 */

                /** 方式二:先刪除,然後在建立一個新的Job  */
                //JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                //Class<? extends Job> jobClass = jobDetail.getJobClass();
                //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
                /** 方式二 :先刪除,然後在建立一個新的Job */
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一個任務
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public  void removeJob(String jobName, String jobGroupName,
                                 String triggerName, String triggerGroupName) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();

            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            sched.pauseTrigger(triggerKey);// 停止觸發器
            sched.unscheduleJob(triggerKey);// 移除觸發器
            sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 刪除任務
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:啟動所有定時任務
     */
    public  void startJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:關閉所有定時任務
     */
    public  void shutdownJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

5、在觸發定時任務時處理自己的邏輯

1、要實現 

 org.quartz.Job 介面中的以下方法
void execute(JobExecutionContext var1) throws JobExecutionException;

2、在 org.quartz.Job介面中的 execute方法中 使用  testService 會出現 testService==null的情況,所以要在

QuartzManager.java 類中的 
addJob方法裡面新增
sched.setJobFactory(myJobFactory);  (很重要)

@Autowired

private TestService testService;

3、java 程式碼實現

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
public class QuartzJobTest implements Job {


    private static final Logger logger= LoggerFactory.getLogger(QuartzJobTest.class);

    @Autowired
    private TestService testService;


    /**
     * 執行 job
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            JobDataMap map =   jobExecutionContext.getJobDetail().getJobDataMap();
            String payCompanyCode= (String) map.get("payCompanyCode");

            PayCompany payCompany=testService.getCompanyByCode(payCompanyCode);

        }catch (Exception e){
            logger.error("QuartzJob execute error",e);
        }
    }

}
如有問題點選這裡   qq