Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the function of Trigger in Quartz

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the role of Trigger in Quartz, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Public properties of Trigger

TriggerKey: an attribute that represents a Trigger identity

The identity of the Job executed when the jobKey:Trigger is triggered

The time when the startTime:Trigger was first triggered

Time point of endTime:Trigger failure

Other properties of Trigger

Priority (priority): if there are too many Trigger, or too few worker threads in the quartz thread pool, Quartz may not have enough resources for colleagues to trigger all Trigger, in this case, if you want some Trigger to be triggered first, you need to set it priority. The default priority of Trigger is 5, and the value of priority priority attribute can be any integer, positive or negative. (priority will only be compared between Trigger triggered at the same time)

Miss trigger (misfire): if Scheduler is turned off, or if there is no thread available in the Quartz thread pool to execute Job, the persistent Trigger will miss its trigger time, that is, miss trigger. Different types of Trigger have different misfire mechanisms, and they all use "intelligent mechanism (smart policy)" by default, that is, dynamically adjust the behavior according to the type and configuration of the Trigger, when the Scheduler starts, query all persistent Trigger of the missed trigger mechanism, and then update the information of the Trigger according to their respective misfire mechanism.

Calendar (Calendar) example

Quartz's Calendar object (not a java.util.Calendar object) can be associated with the trigger when defining and storing the trigger. Calendar is used to exclude time periods from the scheduling plan of trigger.

All kinds of commonly used Trigger

SimpleTrigger

Specifies a task that is executed at intervals (in milliseconds) starting at a certain time.

Its properties are:

RepeatInterval: repeat interval

RepeatCount: the number of repeats, the actual number of execution is repeatCount+1 (because it must be executed once in startTime)

SimpleTrigger trigger = newTrigger () .withIdentity ("trigger1", "group1") .startAt (futureDate (5, DateBuilder.IntervalUnit.SECOND)) .withschedule (simpleSchedule () .withIntervalInSeconds (10) .withRepeatCount (10)) .endAt (dateOf (18,0,0)) .forJob (job) .build ()

Note: the value of the endTime attribute overrides the property value of the repeatCount.

TriggerBuilder (and other Builder of Quartz) will choose reasonable default values for properties that are not displayed, for example, if withIdentity (..) is not called. Method, TriggerBuilder generates a random name for trigger; if startAt (..) is not called Method, the current time is used by default, that is, the trigger takes effect immediately.

CalendarIntervalTrigger

Similar to SimpleTrigger, it specifies a task that starts at a certain time and executes at regular intervals. But the difference is that the time interval specified by SimpleTrigger is millisecond, and there is no way to specify that it is executed every other month (the monthly interval is not a fixed value), while the interval units supported by CalendarIntervalTrigger are seconds, minutes, hours, days, months, years, and weeks.

There are two advantages over SimpleTrigger:

1. It's more convenient. For example, if you execute every hour, you don't have to calculate how many milliseconds an hour equals.

2. Support intervals of non-fixed length, such as month and year. But the disadvantage is that the accuracy can only reach seconds.

Its properties are:

Interval execution interval

Unit of intervalUnit execution interval (seconds, minutes, hours, days, months, years, weeks)

CalendarIntervalTrigger trigger = newTrigger () .withIdentity ("trigger1", "group1") .startNow () .withschedule (calendarIntervalSchedule (). WithInterval (10, DateBuilder.IntervalUnit.SECOND)) / / .withSchedule (calendarIntervalSchedule (). WithIntervalInDays (1)) .endat (dateOf (18,0,0)) .forJob (job) .build ()

DailyTimeIntervalTrigger

Specify that tasks are performed at regular intervals within a certain period of time of each day. And it can support a specified week.

Its properties are:

StartTimeOfDay start time every day

EndTimeOfDay end time of day

The week that daysOfWeek needs to execute

Interval execution interval

Unit of intervalUnit execution interval (seconds, minutes, hours, days, months, years, weeks)

RepeatCount repetition times

DailyTimeIntervalTrigger trigger = newTrigger () .withIdentity ("trigger1", "group1") .startNow () .withschedule (dailyTimeIntervalSchedule () .onDaysOfTheWeek (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY) / execute .withinterval (10, DateBuilder.IntervalUnit.SECOND) .forJob (job) .build () from Monday to Friday.

CronTrigger

Suitable for more complex tasks, it supports syntax of type Linux Cron (and more powerful).

CronTrigger trigger = newTrigger () .withIdentity ("trigger1", "group1") .startNow () .withschedule (cronSchedule ("* / 1 *?")) .forJob (job) .build ()

Note: if some scheduling requirements are too complex to be represented by a single trigger, you should create multiple Trigger,Job and Trigger that are loosely coupled, and a Job can define multiple Trigger.

Public class HelloJob implements Job {@ Override public void execute (JobExecutionContext context) throws JobExecutionException {try {JobDetail job = context.getJobDetail (); String name = job.getJobDataMap () .getString ("name"); Trigger trigger = context.getTrigger (); System.out.println ("Run By Trigger:" + trigger.getKey () + ", hello" + name + "at" + new Date ()) } catch (Exception e) {e.printStackTrace ();} Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler (); scheduler.start (); JobDetail job = newJob (HelloJob.class) .withIdentity ("job1", "group1") .usingJobData ("name", "quartz"). Build () CronTrigger trigger1 = newTrigger () .withIdentity ("trigger1", "group1") .startNow () .withschedule (cronSchedule ("* / 5 * 9-12 * *?")) .forJob (job) .build () CronTrigger trigger2 = newTrigger () .withIdentity ("trigger2", "group1") .startNow () .withschedule (cronSchedule ("0 * / 1 14-18 * *?)) .forJob (job) .build (); Set triggerSet = new HashSet (); triggerSet.add (trigger1); triggerSet.add (trigger2); scheduler.scheduleJob (job, triggerSet, true); try {Thread.sleep (1000L * 60L * 10L) } catch (InterruptedException e) {e.printStackTrace ();} scheduler.shutdown ()

Misfire strategy

MISFIRE_INSTRUCTION_SMART_POLICY: the default MisFire policy for all Trigger, that is, to leave the processing logic to the Quartz from the Smart.

Basic strategy:

> if the schedule is executed only once, use MISFIRE_INSTRUCTION_FIRE_NOW

> for unlimited scheduling (repeatCount is unlimited), use MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT

> otherwise, use MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT

MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY: ignore the MisFire policy and restart all MisFire tasks when resources are appropriate, without affecting the existing scheduling

SimpleTrigger Misfire strategy

MISFIRE_INSTRUCTION_FIRE_NOW: ignore tasks that have already been MisFire, and schedule them immediately, usually only for scenarios where only one task is executed

MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT: set startTime to the current time and reschedule tasks immediately, including tasks for MisFire

MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT: similar to the previous policy, except that it ignores the tasks of MisFire

MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT: restart scheduling tasks, including MisFire tasks, at the point in time of the next schedule

MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT: similar to the previous policy, except that it ignores the tasks of MisFire

CronTrigger Misfire strategy

MISFIRE_INSTRUCTION_DO_NOTHING: do nothing and wait for the next scheduling time to trigger.

MISFIRE_INSTRUCTION_FIRE_NOW: ignore tasks that have already been MisFire, and schedule them immediately, usually only for scenarios where only one task is executed

Listeners

Listener is used to listen for event operations during scheduling, but in most cases, users do not use Listener. The usage of JobListener, TriggerListener and SchedulerListener is similar, except for the operation of addXXXListener () and removeXXXListener (). Here is an example of JobListener:

Create a custom JobListener:

Public class MyJobListener implements JobListener {@ Override public String getName () {System.out.println ("getName ()"); return "getName ()";} @ Override public void jobToBeExecuted (JobExecutionContext jobExecutionContext) {System.out.println ("jobToBeExecuted ()");} @ Override public void jobExecutionVetoed (JobExecutionContext jobExecutionContext) {System.out.println ("jobExecutionVetoed ()") @ Override public void jobWasExecuted (JobExecutionContext jobExecutionContext, JobExecutionException e) {System.out.println ("jobWasExecuted ()");}}

Use JobListener:

Public class JobListenerDemo {public static void main (String [] args) {try {Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler (); MyJobListener myJobListener = new MyJobListener (); / / add listening scheduler.getListenerManager (). AddJobListener (myJobListener, KeyMatcher.keyEquals (jobKey ("job1", "group1")); / / scheduler.getListenerManager (). AddJobListener (new MyJobListener (), GroupMatcher.groupEquals ("group1")) / / remove listening / / scheduler.getListenerManager () .removeJobListener (myJobListener.getName ()); scheduler.start (); JobDetail job = newJob (HelloJob.class) .withidentity ("job1", "group1") .usingJobData ("name", "quartz") .build () Trigger trigger = newTrigger (). WithIdentity ("trigger1", "group1"). StartNow (). Withschedule (simpleSchedule (). WithIntervalInSeconds (1). RepeatForever ()). Build (); scheduler.scheduleJob (job, trigger); try {Thread.sleep (1000L * 60L * 10L);} catch (InterruptedException e) {e.printStackTrace () } scheduler.shutdown ();} catch (SchedulerException e) {e.printStackTrace ();} these are the functions of Trigger in Quartz. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report