quartz的一些記錄

来源:https://www.cnblogs.com/killbug/archive/2018/01/06/8215326.html
-Advertisement-
Play Games

定時任務總會遇到任務重疊執行的情況,比如一個任務1分鐘執行一次,而任務的執行時間超過了1分鐘,這樣就會有兩個相同任務併發執行了。有時候我們是允許這種情況的發生的,比如任務執行的代碼是冪等的,而有時候我們可能考慮到一些情況是不允許這種事情發生的。 在實際場景中,我們定時任務調度使用quartz來實現觸 ...


定時任務總會遇到任務重疊執行的情況,比如一個任務1分鐘執行一次,而任務的執行時間超過了1分鐘,這樣就會有兩個相同任務併發執行了。有時候我們是允許這種情況的發生的,比如任務執行的代碼是冪等的,而有時候我們可能考慮到一些情況是不允許這種事情發生的。

在實際場景中,我們定時任務調度使用quartz來實現觸發的,定時任務的業務代碼分佈在各個應用,用soa調用。

對於quartz來說,官方文檔上明確對這種需求有指定的解決辦法,就是使用註解@DisallowConcurrentExecution;

意思是:禁止併發執行多個相同定義的JobDetail,就是我們想要的。

下麵一個實現的例子:可以對比兩個job:AllowConcurrentExecutionTestJob,DisallowConcurrentExecutionTestJob

public class AllowConcurrentExecutionTestJob implements Job {
    public AllowConcurrentExecutionTestJob() {
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {

        try {
            List<JobExecutionContext> list = context.getScheduler().getCurrentlyExecutingJobs();
            for(JobExecutionContext jobExecutionContext : list){
                // job內部獲取容器內變數
                System.out.println(jobExecutionContext.getJobDetail().getKey().getName());
            }
            Thread.sleep(4000);
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Hello World!  AllowConcurrentExecutionTestJob is executing.");
    }
}
@DisallowConcurrentExecution
public class DisallowConcurrentExecutionTestJob implements org.quartz.Job {
    public DisallowConcurrentExecutionTestJob() {
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {

        try {
            List<JobExecutionContext> list = context.getScheduler().getCurrentlyExecutingJobs();
            for(JobExecutionContext jobExecutionContext : list){
                // job內部獲取容器內變數
                System.out.println(jobExecutionContext.getJobDetail().getKey().getName());
            }
            Thread.sleep(4000);
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Hello World!  DisallowConcurrentExecutionTestJob is executing.");
    }
}

測試代碼:

public class QuartzTest {
    public static void main(String[] args) throws InterruptedException {

        try {
            // Grab the Scheduler instance from the Factory
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            // and start it off
            scheduler.start();

            // define the job and tie it to our HelloJob class
            JobDetail job = JobBuilder.newJob(DisallowConcurrentExecutionTestJob.class)
                    .withIdentity("job1", "group1")
                    .build();

            // Trigger the job to run now, and then repeat every 40 seconds
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startNow()
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(1)
                            .repeatForever())
                    .build();

            // define the job and tie it to our HelloJob class
            JobDetail job2 = JobBuilder.newJob(AllowConcurrentExecutionTestJob.class)
                    .withIdentity("job2", "group1")
                    .build();

            // Trigger the job to run now, and then repeat every 40 seconds
            Trigger trigger2 = TriggerBuilder.newTrigger()
                    .withIdentity("trigger2", "group1")
                    .startNow()
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(1)
                            .repeatForever())
                    .build();

            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job2, trigger2);
//            scheduler.scheduleJob(job2, trigger2);
            // wait trigger
            Thread.sleep(20000);
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        }
    }
}

 

 我們還發現在job的execute里傳參是JobExecutionContext,它可以讓我們拿到正在執行的job的信息。所以我想在job里直接判斷一下就可以知道有沒有已經在執行的相同job。

public class SelfDisAllowConExeTestJob implements org.quartz.Job{
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            List<JobExecutionContext> list = context.getScheduler().getCurrentlyExecutingJobs();
            Set<String> jobs = new HashSet<String>();
            int i=0;
            for (JobExecutionContext jobExecutionContext : list){
                if(context.getJobDetail().getKey().getName().equals(jobExecutionContext.getJobDetail().getKey().getName())){
                    i++;
                }
            }
            if(i>1){
                System.out.printf("self disallow ");
                return;
            }
            Thread.sleep(4000);
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Hello World!  SelfDisAllowConExeTestJob is executing.");

    }
}

測試代碼:

public class OuartzSelfMapTest {

    public static void main(String[] args) throws InterruptedException {

        try {
            // Grab the Scheduler instance from the Factory
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            // and start it off
            scheduler.start();

            // define the job and tie it to our HelloJob class
            JobDetail job = JobBuilder.newJob(SelfDisAllowConExeTestJob.class)
                    .withIdentity("job1", "group1")
                    .build();

            // Trigger the job to run now, and then repeat every 40 seconds
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startNow()
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(1)
                            .repeatForever())
                    .build();

            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);

            // wait trigger
            Thread.sleep(20000);
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        }
    }
}

我們在實際代碼中經常會結合spring,特地去看了一下MethodInvokingJobDetailFactoryBean的concurrent屬性來控制是否限制併發執行的實現:

        Class<?> jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class);
    /**
     * Extension of the MethodInvokingJob, implementing the StatefulJob interface.
     * Quartz checks whether or not jobs are stateful and if so,
     * won't let jobs interfere with each other.
     */
    @PersistJobDataAfterExecution
    @DisallowConcurrentExecution
    public static class StatefulMethodInvokingJob extends MethodInvokingJob {

        // No implementation, just an addition of the tag interface StatefulJob
        // in order to allow stateful method invoking jobs.
    }

當然,在quartz里有一個StatefulJob,方便直接繼承就實現了concurrent=false的事情了。

那麼啰嗦了這麼多,其實就是想表達,quartz里並沒有一個可以設置說是否併發的介面,而是需要自定義的job自行繼承,或使用註解來實現的。

 

另外,還有一個相關的註解:@PersistJobDataAfterExecution

意思是:放在JobDetail 里的JobDataMap是共用的,也就是相同任務之間執行時可以傳輸信息。很容易想到既然是共用的,那麼就會有併發的問題,就如開頭說的這個場景就會導致併發問題。所以官方文檔也特別解釋這個註解最好和@DisallowConcurrentExecution一起使用。

以下是例子:

@PersistJobDataAfterExecution
public class PersistJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap data = context.getJobDetail().getJobDataMap();
        int i = data.getInt("P");
        System.out.printf("PersistJob=>"+i);
        i++;
        data.put("P", i);
    }
}

測試代碼:

public class PersistJobDataQuartzTest {
    public static void main(String[] args) throws InterruptedException {

        try {
            // Grab the Scheduler instance from the Factory
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            // and start it off
            scheduler.start();

            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("P",1);
            // define the job and tie it to our HelloJob class
            JobDetail job = JobBuilder.newJob(PersistJob.class)
                    .withIdentity("job1", "group1").usingJobData(jobDataMap)
                    .build();

            // Trigger the job to run now, and then repeat every 40 seconds
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startNow()
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(1)
                            .repeatForever())
                    .build();

            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);
            // wait trigger
            Thread.sleep(20000);
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        }
    }
}
View Code

 

參考文檔:

https://jayvilalta.com/blog/2014/06/04/understanding-the-disallowconcurrentexecution-job-attribute/ http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-03 http://www.cnblogs.com/lnlvinso/p/4194725.html  
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 代碼以後再補 歐拉函數 我們用$\phi(n)$表示歐拉函數 定義:$\phi(n)$表示對於整數$n$,小於等於$n$中與$n$互質的數的個數 性質 1.$\phi(n)$為積性函數 2.$\sum_{d|n}\phi(d)=n$ 3.$1$到$n$中與$n$互質的數的和為$n*\dfrac{\p ...
  • 凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/ Question: Answer: ...
  • 在Spring核心配置文件中沒有增加事務方法,導致以上問題 Action類UserAction UserService類 UserDao介面 UserDaoImplements類 User實體類: web.xml 自動啟動監聽和過濾器 Spring核心配置文件bean.xml 通過引入各個分模塊 分 ...
  • Python創建類的時候為什麼要繼承新式類?看完這篇文章或許你就明白了。 ...
  • CRM項目總結 一:開發背景 在公司日益擴大的過程中,不可避免的會伴隨著更多問題出現。 對外 : 如何更好的管理客戶與公司的關係?如何更及時的瞭解客戶日益發展的需求變化?公司的產品是否真的符合客戶需求?以及公司新產品信息是否更有針對性的及時推送給客戶?客戶沒有 對內 : 公司發展壯大,部門越來越多, ...
  • 前言 本人在通過《C語言程式設計:現代方法(第2版)》自學C語言時,發現國內並沒有該書完整的課後習題答案,所以就想把自己在學習過程中所做出的答案分享出來,以供大家參考。這些答案是本人自己解答,並參考GitHub上相關的分享和Chegg.com相關資料。因為並沒有權威的答案來源,所以可能會存在錯誤的地 ...
  • 用以前學過的知識,可以簡單地做一個超市庫存管理系統: 定義一個商品類: 然後: ...
  • 首先是打開Content Assistant,自動代碼補全 Window Preferences Java Editor Content Assist,在最下麵的Auto Activation區域的Auto activation triggers for java裡面把26個英文字母都敲一遍 CTR ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...