Quartz動態管理一次性定時任務(Spring)

本次實現採用的是簡陋的Quartz實現。在Spring容器中配好相應的組件包。不採用配置文件實現每天定時循環任務,本次實現的是一次性定時。(幾天後執行一個操作,操作完成後刪除該定時,每次操作的內容不相同)。在執行任務的時候注入Spring管理的對象。
1、動態的添加刪除定時任務

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.context.ApplicationContext;
public class TriggerManager {
    /**
     * 添加定時任務
     * @param JobName 工作名稱,可任意定義,不重複
     * @param JobGroupName 工作組名稱,建議統一規劃,可重複
     * @param time 啓動的時間
     * @param jobClass 要執行的工作類
     * @param parameter 傳遞的參數
     * @param servletContent application對象,取得spring bean對象的關鍵
     */
    @SuppressWarnings({ "deprecation" })
    public static void addJob(String JobName, String JobGroupName, String time,
            Class<? extends Job> jobClass,String parameter,ApplicationContext servletContent) {
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobDetail jobDetail = new JobDetailImpl(JobName, JobGroupName,
                    jobClass);// 任務名,任務組,任務執行類
            jobDetail.getJobDataMap().put("jobName", parameter);
            jobDetail.getJobDataMap().put("servletContent", servletContent);
            CronTrigger trigger = new CronTriggerImpl(JobName, JobGroupName,
                    time);// 觸發器名,觸發器組,觸發時間
            scheduler.scheduleJob(jobDetail, trigger);// 將任務信息添加到sheduler中
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void delJob(String JobName, String JobGroupName) {
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            TriggerKey triggerKey = new TriggerKey(JobName, JobGroupName);
            JobKey jobKey = new JobKey(JobName, JobGroupName);
            scheduler.pauseTrigger(triggerKey);// 停止觸發器
            scheduler.unscheduleJob(triggerKey);// 刪除觸發器
            scheduler.deleteJob(jobKey);// 刪除任務
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

2、添加定時任務

@Deprecated 
    private void test(){
        //在任意地方取得application對象
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
        ServletContext servletContext = webApplicationContext.getServletContext();  
        ApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        String time = null;
        try {
            time = ConversionTime.conversionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-01-01 01:01"));
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        TriggerManager.addJob("test","default", time,com.shcedule.JTest.class,"test",application);
        Scheduler scheduler = null;
        try {
            //添加並啓動
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

3、執行動態定時測試類

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap= context.getJobDetail().getJobDataMap();
        String jobName = dataMap.getString("jobName");
        ApplicationContext servletContext = (ApplicationContext) dataMap.get("servletContent");
        JTest test= servletContext.getBean(JTest.class);
        try {
            System.out.println("jobName"+jobName);
            test.sendMessage("crazy");
        } catch (Exception e) {
            e.printStackTrace();
        }
        TriggerManager.delJob(jobName,jobName);
    }
}

以上就可以實現動態的添加刪除不同的一次性定時任務。
備註:如果要在Spring啓動時完成這樣的一次定時任務添加,需要注意必須等待Spring加載完畢後,ContextLoader.getCurrentWebApplicationContext()才能獲取到對應的servletContext 實例對象,如果發現加載時取不到,可以用線程等待休眠一段時間,等Spring容器先加載完畢後,即可獲取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章