In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use Java task scheduling framework Quartz". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Compared to Timer, Quartz adds a lot of features to Quartz:
Persistent jobs-that is, to maintain the state of scheduling timing
Job management-effective management of scheduled jobs
1 、 Quartz
1.1 introduction of dependency
Org.quartz-scheduler quartz 2.3.2 org.quartz-scheduler quartz-jobs 2.3.21.2 getting started
Task: execute the task class 10 times with an interval of 3 seconds each time.
Task class, you need to implement the Job interface
Package com.sugar.quartz.utils;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import java.text.SimpleDateFormat;import java.util.Date;/** * function description: task * * @ author XiaoNianXin * @ date 20:52 on 2021-12-13 * / public class HelloJob implements Job {@ Override public void execute (JobExecutionContext context) throws JobExecutionException {/ / get the current time and format Date date = new Date () SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); String dateSrting = format.format (date); / / Business function simulates System.out.println ("start backup database, time:" + dateSrting);}} timer class
Package com.sugar.quartz.utils;import org.quartz.*;import org.quartz.impl.StdSchedulerFactory;/** * function description: timer configuration * * @ author XiaoNianXin * @ date 21:08 on 2021-12-13 * / public class HelloSchedulerDemo {public static void main (String [] args) throws SchedulerException {/ / 1, Scheduler-get scheduling instance from factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler () / / 2. Task instance-Task object JobDetail job = JobBuilder.newJob (HelloJob.class) .withIdentity ("job1", "group1") / / Task name, group name .build () / / 3, trigger-controls the number of execution times and execution time Trigger trigger = TriggerBuilder.newTrigger () .withIdentity ("trigger1", "group1") / / ditto .startNow () / / start .withschedule (SimpleScheduleBuilder.simpleSchedule ()) immediately. WithIntervalInSeconds (3). WithRepeatCount (10)) / / cycle 10 times at intervals of 3s. Build (); / / Scheduler associates triggers and starts scheduler.scheduleJob (job,trigger); scheduler.start ();} 1.3 Job and JobDetail
Job: a reflection-based task scheduling interface that all task classes implement and write their own business logic in the execute of the interface.
Job lifecycle: each time Job is executed, a new Job instance is created before the execute method. After the instance is called, the instance is released and then reclaimed by GC.
JobDetail: encapsulates Job, providing many properties to Job instances.
JobDetail attributes: name, group, jobClass, jobDataMap.
1.4 JobExecutionContext
Hereafter, JobExecutionContext is abbreviated as JEC.
JEC: when the scheduler calls Job, it passes JEC to the execute method of Job.
The role of JEC: Job obtains the running environment information and Job information through JEC.
1.5 JobDataMap
Hereafter, JobDataMap is abbreviated as JDM.
JDM: when a task is scheduled, the JDM is stored in JEC for easy access.
JDM advantages: implement the Map interface, you can access any serializable object, Job execution will pass parameters to JDM.
Obtain JDM parameter cases manually
HelloSchedulerDemo:
Package com.sugar.quartz.utils;import org.quartz.*;import org.quartz.impl.StdSchedulerFactory;/** * function description: timer configuration * * @ author XiaoNianXin * @ date 21:08 on 2021-12-13 * / public class HelloSchedulerDemo {public static void main (String [] args) throws SchedulerException {/ / 1, Scheduler-get scheduling instance from factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler () / / 2. Task instance-Task object JobDetail job = JobBuilder.newJob (HelloJob.class) .withIdentity ("job1", "group1") / / Task name, group name .usingJobData ("msg", "JDM uses-Detail") / / JDM passes parameters .build () / / 3, trigger-controls the number of execution times and execution time Trigger trigger = TriggerBuilder.newTrigger () .withIdentity ("trigger1", "group1") / / ditto .startNow () / / start .withschedule (SimpleScheduleBuilder.simpleSchedule ()) immediately. WithIntervalInSeconds (3). WithRepeatCount (10)) / / cycle 10 times at intervals of 3s .usingJobData ("msg", "JDM uses-Trigger") .build (); / / the scheduler associates triggers and starts scheduler.scheduleJob (job,trigger); scheduler.start ();}}
HelloJob:
Package com.sugar.quartz.utils;import org.quartz.Job;import org.quartz.JobDataMap;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import java.text.SimpleDateFormat;import java.util.Date / * feature description: timing service function * * @ author XiaoNianXin * @ date 20:52 on 2021-12-13 * / public class HelloJob implements Job {@ Override public void execute (JobExecutionContext context) throws JobExecutionException {/ / get the current time and format Date date = new Date (); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); String dateSrting = format.format (date) / / get JDM JobDataMap Detail_JDM = context.getJobDetail () .getJobDataMap (); JobDataMap Trigger_JDM = context.getTrigger () .getJobDataMap (); String detail_jdmString = Detail_JDM.getString ("msg"); String trigger_jdmString = Trigger_JDM.getString ("msg") System.out.println ("- -"); System.out.println ("detail_jdmString =" + detail_jdmString); System.out.println ("trigger_jdmString =" + trigger_jdmString) / / Business function simulates System.out.println ("start backup database, time:" + dateSrting); / / other content System.out.println ("Job run time:" + context.getJobRunTime ()); System.out.println ("Job current run time:" + context.getFireTime ()) System.out.println ("Job next run time:" + context.getNextFireTime ()); System.out.println ("- -");}} 2. The Job class implements the Setter method of the JDM parameter, and automatically binds the parameter when instantiated.
HelloJob:
/ / automatically bind the value private String msg;public void setMsg (String msg) {this.msg = msg;} / / corresponding to JDM key when instantiating to get JDMSystem.out.println (Trigger JDM: "+ msg)
Question: the key of JDM in JobDetail and Trigger above is "msg". Which one is this msg?
E.G: the value of JobDetail will be overwritten if you encounter key,Trigger with the same name, so msg is the value of Trigger JDM.
1.6 Job statu
Stateful Job: the same JDM is shared during multiple calls to Job.
Stateful Job: create a new JDM each time during multiple calls to Job.
Distinguishing cases with stateless Job
Expectation: stateless count output is always 1, stateful count output accumulates.
HelloSchedulerDemo:
/ / JobDeatil add a JDM to use as a counter .usingJobData ("count", 0)
Stateless HelloJob:
Package com.sugar.quartz.utils;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import java.text.SimpleDateFormat;import java.util.Date;/** * function description: task class * * @ author XiaoNianXin * @ date 20:52 on 2021-12-13 * / public class HelloJob implements Job {/ / automatically bind the value private String msg; private Integer count corresponding to JDM key when instantiation Public void setMsg (String msg) {this.msg = msg;} public void setCount (Integer count) {this.count = count;} @ Override public void execute (JobExecutionContext context) throws JobExecutionException {/ / get the current time and format Date date = new Date (); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); String dateSrting = format.format (date) / / get JDM System.out.println ("- -"); System.out.println ("Trigger JDM:" + msg); System.out.println ("Count:" + count) / / update count count++; context.getJobDetail () .getJobDataMap () .put ("count", count) of JobDetail JDM; / / Business function simulates System.out.println ("start backup database, time:" + dateSrting); / / other content System.out.println ("Job run time:" + context.getJobRunTime ()) System.out.println ("Job current run time:" + context.getFireTime ()); System.out.println ("Job next run time:" + context.getNextFireTime ()); System.out.println ("- -");}}
Stateful HelloJob:
/ / the task class, with the following comments, calls Job multiple times, and the data that persists Job,JDM will be saved for next time using @ PersistJobDataAfterExecution1.7 Trigger
Trigger commonly used: SimpleTrigger, CronTrigger.
The JobKey:Job instance is identified. When the trigger is triggered, the JobKey corresponding task is executed.
StartTime: the first trigger time.
EndTime: the trigger time is terminated.
A case of obtaining parameters by Trigger
HelloSchedulerTriggerDemo:
Package com.sugar.quartz.utils;import org.quartz.*;import org.quartz.impl.StdSchedulerFactory;import java.util.Date;/** * function description: timer configuration 2 * * @ author XiaoNianXin * @ date, 2021-12-13 21:08 * / public class HelloSchedulerTriggerDemo {public static void main (String [] args) throws SchedulerException {/ / task start time delayed by 3 s, end time delayed by 10 s Date startData = new Date () StartData.setTime (startData.getTime () + 3000); Date endData = new Date (); endData.setTime (endData.getTime () + 10000); / / 1, Scheduler-get scheduling instance from factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler () / / 2. Task instance-Task object JobDetail job = JobBuilder.newJob (helloJobTrigger.class) .withIdentity ("job1", "group1") / / Task name, group name .usingJobData ("msg", "JDM uses-Detail") / / JDM passes parameters .build () / / 3. Trigger-controls the number of execution times and execution time Trigger trigger = TriggerBuilder.newTrigger () .withidentity ("trigger1", "group1") / / Ibid. StartNow () / / start .startAt (startData) .endAt (endData) .build () immediately. / / Scheduler associates triggers and starts scheduler.scheduleJob (job,trigger); scheduler.start ();}}
HelloJobTrigger:
Package com.sugar.quartz.utils;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.PersistJobDataAfterExecution;import java.text.SimpleDateFormat;import java.util.Date / * function description: task class 2 * * @ author XiaoNianXin * @ date 20:52 on 2021-12-13 * / @ PersistJobDataAfterExecutionpublic class helloJobTrigger implements Job {@ Override public void execute (JobExecutionContext context) throws JobExecutionException {/ / get the current time and format Date date = new Date (); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); String dateSrting = format.format (date) / / Business function simulation System.out.println ("- -"); System.out.println ("start backup database, time:" + dateSrting) / / get JobKey,StartTime,EndTime System.out.println ("JobKey:" + context.getTrigger (). GetJobKey ()); System.out.println ("StartTime:" + format.format (context.getTrigger (). GetStartTime ()); System.out.println ("EndTime:" + format.format (context.getTrigger (). GetEndTime () System.out.println ("- -") }} / / run result-start backing up the database Time: 2021-12-13 23:25:06JobKey: group1.job1StartTime: 2021-12-13 23:25:06EndTime: 2021-12-13 22-13-13-25-13-13-13-13-13-13-12-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-13-12-13 SimpleTripper
Hereafter, SimpleTripper is abbreviated as ST.
ST: a specific time range starts / ends, and the Job design is repeated n times at a time interval.
ST attributes: start time, end time, number of repeats, and interval.
ST hint: if the end time is specified, then the end time priority > the number of repeats.
This is the end of the content of "how to use the Java Task scheduling Framework Quartz". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.