Quartz Concurrent/Single thread

Source: Internet
Author: User

Quartz Concurrent/Single thread

Quartz timed tasks are performed concurrently by default, and do not wait for the last task to complete, as long as the interval is over, and if the timing is too long, it will take up resources and cause other tasks to become clogged.
1. In spring, you need to set the value of concurrent to false, which disables concurrent execution.

<property name= "Concurrent" value= "true"/>

2. When you do not use spring, you need to add @disallowconcurrentexecution comments to the job implementation class
@DisallowConcurrentExecution prohibit concurrent execution of multiple jobdetail of the same definition, this annotation is added to the job class, but it does not mean that multiple jobs cannot be executed concurrently, but that the same job definition cannot be executed concurrently ( Defined by Jobdetail), but can execute several different jobdetail at the same time, for example, we have a job class called Sayhellojob, and add this annotation to this job, and then define a lot of jobdetail on this job, such as Sayhellotojoejobdetail, Sayhellotomikejobdetail, then when the scheduler is started, Multiple sayhellotojoejobdetail or sayhellotomikejobdetail are not executed concurrently, but Sayhellotojoejobdetail and Sayhellotomikejobdetail can be executed concurrently

@PersistJobDataAfterExecution is also added to the job, indicating that the data in the Jobdatamap should be changed to be used for the next call when the job is done normally. When using @persistjobdataafterexecution annotations, in order to avoid concurrency, storing data is confusing, it is strongly recommended to add @disallowconcurrentexecution annotations.

@DisallowConcurrentExecution

This tag is used on the class that implements the job, which means that concurrent execution is not allowed, as I have previously understood, that the dispatch framework is not allowed to invoke the job class at the same time, and that it is not, but that the job (task) execution time [for example, 10 seconds] is greater than the time interval of the task [ Interval (5 seconds)], by default, the scheduling framework enables new threads to perform tasks in order to allow the task to execute at our scheduled intervals. Otherwise, it will wait for the task to complete and then execute again! (This will result in the execution of the task not being performed at our predefined intervals)

Test the code, which is an official example. The time interval is set at 3 seconds, but the job execution time is 5 seconds, the program will wait for the task to execute after the completion of the @disallowconcurrentexecution, or the new thread execution will be enabled in 3 seconds.

Org.quartz.threadPool.threadCount = 5 Here Configure the number of threads in the thread pool of the framework to configure several more, otherwise @disallowconcurrentexecution does not work
Org.quartz.scheduler.instanceName = MySchedulerorg.quartz.threadPool.threadCount = 5org.quartz.jobstore.class = Org.quartz.simpl.RAMJobStore
/* * Copyright 2005-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); The * use of this file except-compliance with the License.  Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicable Law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, without * Warra Nties or CONDITIONS of any KIND, either express OR implied. See the * License for the specific language governing permissions and limitations * under the License. * */package org.quartz.examples.example5;import Java.util.date;import org.quartz.DisallowConcurrentExecution; Import Org.quartz.job;import Org.quartz.jobdatamap;import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import org.quartz.persistjobdataafterexecution;/** * <p> A Dumb Implementation of JOB, for unit testing purposes. </p> * * @author James House * * @PersistJobDataAftErexecution@disallowconcurrentexecutionpublic class Statefuldumbjob implements Job {/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Constants. * * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */public static final String NUM_EX    Ecutions = "Numexecutions";    public static final String Execution_delay = "Executiondelay";     /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * constructors.    * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */public Statefuldumbjob () {}     /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Interface.  * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *//** * <p> Called by the <code>{@link org.quartz.scheduler}</code> When a <code>{@link org.quartz.trigger}</code> Fires is aSsociated with the <code>job</code>.     </p> * * @throws jobexecutionexception If there is a exception while executing the job. */public void execute (jobexecutioncontext context) throws Jobexecutionexception {System.err.println ("---" + Co Ntext.getjobdetail (). GetKey () + "executing.        ["+ New Date () +"] ");        Jobdatamap map = Context.getjobdetail (). Getjobdatamap ();        int executecount = 0;        if (Map.containskey (num_executions)) {Executecount = Map.getint (num_executions);        } executecount++;        Map.put (Num_executions, Executecount);        Long delay = 5000l;        if (Map.containskey (Execution_delay)) {DELAY = Map.getlong (Execution_delay);        } try {thread.sleep (delay); } catch (Exception ignore) {} System.err.println ("-" + context.getjobdetail (). GetKey () + "complete (" + E    Xecutecount + ")."); }}
/* * Copyright 2005-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); The * use of this file except-compliance with the License.  Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicable Law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, without * Warra Nties or CONDITIONS of any KIND, either express OR implied. See the * License for the specific language governing permissions and limitations * under the License. * */package org.quartz.examples.example5;import static org.quartz.jobbuilder.newjob;import static Org.quartz.simpleschedulebuilder.simpleschedule;import static Org.quartz.triggerbuilder.newtrigger;import Static Org.quartz.datebuilder.*;import Java.util.date;import Org.quartz.jobdetail;import Org.quartz.Scheduler;import Org.quartz.schedulerfactory;import Org.quartz.schedulermetadata;import Org.quartz.SimpleTriggEr;import org.quartz.impl.stdschedulerfactory;import Org.slf4j.logger;import org.slf4j.loggerfactory;/** *  Demonstrates the behavior of <code>statefuljob</code>s, as well as how misfire instructions affect the firings of triggers of <code>StatefulJob</code> s-when the jobs take longer to execute that the frequency of the TR Igger ' s repitition. * * <p> While the example was running, you should note that there be, and triggers with identical schedules, firing Identical jobs. The triggers "want" to fire every 3 seconds, and the jobs take seconds to execute. Therefore, by the time of the jobs complete their execution, the triggers has already "misfired" (unless the Scheduler ' s "mi Sfire threshold "have been set to more than 7 seconds). You should see that one of the jobs have its misfire instruction set to <code>simpletrigger.misfire_instruction_resch Edule_now_with_existing_repeat_count</code&gt, which causes it to fire immediately, when the misfire IS detected. The other trigger uses the default "smart policy" misfire instruction, which causes the trigger-advance to its next fir E time (skipping those that it had missed)-so it does not refire immediately, but rather at the next scheduled time . </p> * * @author <a href= "mailto:[email protected]" >chris bonham</a> */public class misfireexample {public void run () throws Exception {Logger log = Loggerfactory.getlogger (Misfireexample.class)        ;        Log.info ("-------Initializing-------------------");        First we must get a reference to a scheduler schedulerfactory SF = new Stdschedulerfactory ();        Scheduler sched = Sf.getscheduler ();        Log.info ("-------Initialization complete-----------");        Log.info ("-------scheduling Jobs-----------");        Jobs can be scheduled before start () have been called//get a ' nice round ' time a few seconds in the ... Date startTime = Nextgivenseconddate (null, 15); STATEFULJOB1 would run every three seconds//(but it'll delay for ten seconds) jobdetail job = Newjob (S Tatefuldumbjob.class). Withidentity ("StatefulJob1", "group1"). Usingjobdata (Statefuldumbjob.execution_delay,        10000L). build (); Simpletrigger trigger = Newtrigger (). Withidentity ("Trigger1", "group1"). StartAt (StartTime). Withschedule (        Simpleschedule (). Withintervalinseconds (3). RepeatForever ()). build ();        Date ft = sched.schedulejob (job, trigger); Log.info (Job.getkey () + "would run at:" + ft + "and repeat:" + trigger.getrepeatcount () + "times, every" + trigger.ge        Trepeatinterval ()/+ + "seconds");        Log.info ("-------starting Scheduler----------------");        Jobs don ' t start firing until start () has been called ... sched.start ();        Log.info ("-------Started Scheduler-----------------");            try {//sleep for ten minutes-triggers to file ....        Thread.Sleep (600L * 1000L); } CAtch (Exception e) {} log.info ("-------shutting down---------------------");        Sched.shutdown (TRUE);        Log.info ("-------Shutdown complete-----------------");        Schedulermetadata metaData = Sched.getmetadata ();    Log.info ("Executed" + metadata.getnumberofjobsexecuted () + "jobs.");        public static void Main (string[] args) throws Exception {Misfireexample example = new Misfireexample ();    Example.run (); }}

@PersistJobDataAfterExecution

This flag indicates that the fixed data in Jobdatamap is saved after the execution method of the job is executed, and each job has a separate jobdatamap by default when no @PersistJobDataAfterExecution is set.

Otherwise the task will have the same jobdatamap when repeated execution

/* * Copyright 2005-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); The * use of this file except-compliance with the License.  Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicable Law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, without * Warra Nties or CONDITIONS of any KIND, either express OR implied. See the * License for the specific language governing permissions and limitations * under the License. * */package Com.quartz.demo.example6;import Java.util.date;import Org.quartz.disallowconcurrentexecution;import Org.quartz.job;import Org.quartz.jobdatamap;import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import Org.quartz.jobkey;import org.quartz.persistjobdataafterexecution;@ Persistjobdataafterexecution@disallowconcurrentexecutionpublic class BadJob1 implements Job {public badJob1 () {} public void execute (jobexecutioncontext context) throws Jobexecutionexception {Jobkey Jobkey = Co        Ntext.getjobdetail (). GetKey ();        Jobdatamap DataMap = Context.getjobdetail (). Getjobdatamap ();        int denominator = Datamap.getint ("denominator");        SYSTEM.OUT.PRINTLN ("---" + jobkey + "executing at" + new Date () + "with denominator" + denominator);        denominator++;    Datamap.put ("denominator", denominator); }}

/* * Copyright 2005-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); The * use of this file except-compliance with the License.  Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicable Law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, without * Warra Nties or CONDITIONS of any KIND, either express OR implied. See the * License for the specific language governing permissions and limitations * under the License. * */package com.quartz.demo.example6;import static org.quartz.jobbuilder.newjob;import static Org.quartz.simpleschedulebuilder.simpleschedule;import static Org.quartz.triggerbuilder.newtrigger;import Static Org.quartz.datebuilder.*;import Java.util.date;import Org.quartz.jobdetail;import Org.quartz.Scheduler;import Org.quartz.schedulerfactory;import Org.quartz.simpletrigger;import Org.quartz.impl.StdSchedulerFaCtory;public class Jobexceptionexample {public void run () throws Exception {//First we must get a reference t        o a scheduler schedulerfactory SF = new Stdschedulerfactory ();        Scheduler sched = Sf.getscheduler ();        Jobs can be scheduled before start () have been called//get a ' nice round ' time a few seconds in the ...        Date startTime = Nextgivenseconddate (null, 2);        Jobdetail job = Newjob (Badjob1.class). Withidentity ("BadJob1", "group1"). Usingjobdata ("denominator", "0"). Build (); Simpletrigger trigger = Newtrigger (). Withidentity ("Trigger1", "group1"). StartAt (StartTime). Withschedule (        Simpleschedule (). Withintervalinseconds (2). RepeatForever ()). build ();        Date ft = sched.schedulejob (job, trigger);        The task executes every 2 seconds then the JOBDATAMAP data obtained in the BadJob1 method is shared.        One thing to note here is that JOBDATAMAP data sharing is only for one BADJOB1 task. If you add a new task below then they are not shared between them such as the following jobdetail job2 = Newjob (Badjob1.class). Withidentity ("BadJob1", "group1"). UsinGjobdata ("Denominator", "0"). Build (); Simpletrigger trigger2 = Newtrigger (). Withidentity ("Trigger1", "group1"). StartAt (StartTime). Withschedule (        Simpleschedule (). Withintervalinseconds (2). RepeatForever ()). build ();        This job2 is not shared with job execution Jobdatamap Sched.schedulejob (JOB2, Trigger2);        Sched.start ();        try {//sleep for-seconds thread.sleep (30L * 1000L);    } catch (Exception e) {} sched.shutdown (false); } public static void Main (string[] args) throws Exception {Jobexceptionexample example = new Jobexceptionexampl        E ();    Example.run (); }}

Quartz Concurrent/Single thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.