An example of a spring Scheduler (Quartz) dynamic Add, delete, modify task

Source: Internet
Author: User

Requirements


Perform an indefinite number of scheduled tasks according to the task list. and need to dynamically add, delete, modify the task.


Code


Public class jobexample {     public static void main ( String[] args)  throws Exception {        //  Job configuration information, which can be obtained from the database or the configuration file         list<jobparameter> list  = new ArrayList<JobParameter> (        string);  jobGroup =  "JobGroup1";        for  (int i  = 1; i < 4; i++)  {             jobparameter param = new jobparameter ();             param.setjobname ("Job"  + i);             param.setjobgroup (Jobgroup);           &nbSp; param.setcronexpression ("0/5&NBSP;*&NBSP;*&NBSP;*&NBSP;*&NBSP;?");             param.setdescription ("Execute job   " + i + "  every 5 seconds&nbsp ... ");             list.add (param);         }         AbstractApplicationContext context = new  Classpathxmlapplicationcontext ("Dynamic-jobs.xml");         try {             Scheduler scheduler =  ( Scheduler)  context.getbean ("Scheduler");             // ###  Create and start job ###             for  (Jobparameter param : lisT)  {                //   Build Job Information                  Jobdetail jobdetail = jobbuilder.newjob (Myjob.class)                          . Withidentity (Param.getjobname (),  param.getjobgroup ()). Build ();                 //  Expression Scheduler Builder                  cronschedulebuilder schedulebuilder =  cronschedulebuilder.cronschedule (Param.getcronexpression ());                 //  build trigger    by cronexpression expression               crontrigger trigger = triggerbuilder.newtrigger (). Withidentity (Param.getjobname (),  param.getjobgroup ())                          .withschedule ( Schedulebuilder). Build ();                 //  put parameters, run-time method can get                  jobdetail.getjobdatamap (). Put ("Jobparam",  param);                 scheduler.schedulejob (jobDetail,  Trigger);            }             // ###  Remove job3 ###           &nBsp; thread.sleep (;            ) System.out.println ("###  remove job3 ###");             scheduler.deletejob (Jobkey.jobkey ("Job3",  jobgroup));             // ###  suspension of Job1 and job2 ###             thread.sleep (;         )    system.out.println ("###  pause Job1 and job2 ###");             scheduler.pausejob (Jobkey.jobkey ("Job1",  jobgroup));             scheduler.pausejob (JobKey.jobKey ("Job2",  Jobgroup));            // ###  Start again Job1  ###     &nbsP;      thread.sleep (;        )     system.out.println ("###  start job1 ### again");             scheduler.resumejob (Jobkey.jobkey ("Job1",  jobgroup));             // ###  Modify JOB1 's cron ###             thread.sleep (;     )        system.out.println ("###  modifies Job1 's cron to perform  ### every 3 seconds");             TriggerKey triggerKey =  Triggerkey.triggerkey ("Job1",  jobgroup);             cronschedulebuilder schedulebuilder = cronschedulebuilder.cronschedule ("0/3 *  * * * ? ");             crontrigger trigger =  ( Crontrigger)  scheduler.gettrigger (Triggerkey);             trigger = trigger.gettriggerbuilder (). withidentity (TriggerKey). WithSchedule ( Schedulebuilder). Build ();            //  Get the job parameters and modify the description             jobparameter jobparam  =  (Jobparameter)  scheduler.getjobdetail (Jobkey.jobkey ("Job1",  jobgroup))                                                                        .getjobdatamap (). Get (Jobparameter.job_param);             jobparam.setcronexpression ("0/3&NBSP;*&NBSP;*&NBSP;*&NBSP;*&NBSP;?");             jobparam.setdescription ("Execute  JOB&NBSP;1&NBSP;EVERY&NBSP;3&NBSP;SECONDS&NBSP, ... ");             scheduler.reschedulejob (Triggerkey, trigger);             //  Print all  Job          in memory    thread.sleep (;            ) System.out.println ("###  the status of all  job in print memory  ###");             set<triggerkey> triggerkeys = scheduler.gettriggerkeys ( Groupmatcher.anytriggergroup ()); &NBSP;&NBsp;          for  (triggerkey tkey :  Triggerkeys)  {                 CronTrigger t =  (Crontrigger)  scheduler.gettrigger (TKey);                 system.out.println ("Trigger  details:  " + t.getjobkey (). GetName ()  + ",  " + t.getjobkey (). Getgroup ()                          +  ", "  + scheduler.gettriggerstate (tKey)  +  " ,  " + t.getfinalfiretime ()  + ",  "                         +  T.getcronexpression ()); &NBSP;&Nbsp;          }         } finally {            if  ( Context != null)  {                 context.close ();             }            system.out.println ("Spring  context is closed. ");         }    }}
public class jobparameter {    public  static final String JOB_PARAM =  "Jobparam";     private  String jobName;    private String jobGroup;     private string jobtrigger;    private string status;     private string cronexpression;    private boolean issync =  false;    private String description;    private  Date updatedtime = new date ();    getter & setter  ...}
public class myjob implements job {    public void  Execute (jobexecutioncontext jobexecutioncontext)  throws JobExecutionException {         JobParameter jobParam =  (Jobparameter)   Jobexecutioncontext.getjobdetail (). Getjobdatamap ()                  .get (Jobparameter.job_param);         if  (jobparam != null)  {             system.out.println (Jobparam.getdescription ());         }  else {            system.out.println (" Hey, can ' t find job parameter :) ");         }    }}


Dynamic-jobs.xml

<bean id= "Scheduler" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean"/>


Execution results


Execute Job 1 every 5 seconds ...

Execute Job 2 every 5 seconds ...

Execute Job 3 every 5 seconds ...

# # # removal JOB3 # # #

Execute Job 1 every 5 seconds ...

Execute Job 2 every 5 seconds ...

# # # Pause Job1 and Job2 # # #

# # # starts again job1 # # #

Execute Job 1 every 5 seconds ...

Execute Job 1 every 5 seconds ...

# # # Modify JOB1 cron to execute once every 3 seconds # # #

Execute Job 1 every 3 seconds ...

Execute Job 1 every 3 seconds ...

# # # Print the status of all jobs in memory # # #

Execute Job 1 every 3 seconds ...

Trigger details:job1, JobGroup1, NORMAL, NULL, 0/3 * * * *?

Trigger details:job2, JobGroup1, PAUSED, NULL, 0/5 * * * *?


Version information


Quartz version: 2.2.1

Spring Version: 3.2.13


Resources


Http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-quartz

http://www.meiriyouke.net/?p=82


Complete example code see attachment


An example of a spring Scheduler (Quartz) dynamic Add, delete, modify task

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.