Java implementation of scheduled tasks in Web Applications (example explanation)

Scheduled task is the function of specifying a future time range to execute a certain task. In current web applications, most applications have task scheduling function. For different voice and different operating systems, they have their own syntax and solutions. Windows operating system calls it task planning. Cron service in Linux provides this function, which is often involved in our business system development. This chat will use java language to complete the use of common timing tasks in daily development work, hoping to bring help to your work and study.

1、 Scheduled task scenario

(1) Drive processing workflow

As a new advance payment order, it is initialized and placed. If the order is not paid within the specified time, it will be considered as a timeout order and closed; There are many applications in the e-commerce system. Users purchase goods and generate orders, but do not pay. If the orders are not paid within 30 minutes, the orders will be closed (and the number of satisfying the scenario is large), so manual intervention is impossible.

(2) System maintenance

The scheduling will obtain the system exception log and store some key point data in the database, dump it to the database at 11:30 pm every working day (except holidays and weekdays), generate an XML file and send it to an employee's mailbox.

(3) Provide reminder service within the application.

The system regularly reminds the login user to perform relevant work at a certain time point.

(4) Scheduled reconciliation task

For the business between the company and the third-party companies (operators, banks, etc.), the reconciliation of the business of the day shall be carried out after 0:00 every day, the reconciliation information and result data shall be sent to the mailbox of the relevant person in charge, and the mismatched data shall be processed during the working hours of the next day.

(5) Data statistics

There are many data records. Reading and querying from the database in real time will produce a certain time for customer experience and performance needs. Therefore, the data will be summarized every week (day, hour), so that the data can be presented quickly when displaying the data.

There are many scenarios for using timed tasks It seems that timed tasks are really widely used in our daily development

2、 Explanation of mainstream timed task technology timer

I believe everyone is already very familiar with Java util. Timer is the simplest method to implement task scheduling. A specific example is given below:

/**Output result: execute job1 execute job1 execute job2 execute job1 execute job1 execute job2*/

The core classes of task scheduling using timer are timer and TimerTask. Timer is responsible for setting the start interval and execution time of TimerTask. Users only need to create an inherited class of TimerTask, implement their own run method, and then throw it to timer for execution. The design core of timer is a tasklist and a taskthread. Timer drops the received tasks into its own tasklist, which is sorted according to the initial execution time of the tasks. Timerthread will start as a daemon thread when creating timer. This thread will poll all tasks, find a task to be executed recently, and then sleep. When the start time point of the task to be executed recently is reached, timerthread will wake up and execute the task. After that, timerthread updates the latest task to be executed and continues to sleep.

The advantage of timer is that it is easy to use. However, since all tasks are scheduled by the same thread, all tasks are executed serially. Only one task can be executed at the same time. The delay or exception of the previous task will affect the subsequent tasks (this should be noted).

ScheduledExecutor

In view of the above defects of timer, Java 5 launched a scheduled executor based on thread pool design. The design idea is that each scheduled task will be executed by a thread in the thread pool, so the tasks are executed concurrently and will not be disturbed. It should be noted that only when the execution time of the task comes, the scheduledexecutor will really start a thread, and the scheduledexecutor will poll the status of the task for the rest of the time.

The above code shows the two most commonly used scheduling methods scheduleatfixedrate and schedulewithfixeddelay in the scheduledexecutorservice. Each execution time of scheduleatfixedrate is a time interval pushed back from the beginning of the last task, that is, each execution time is: initialdelay, initialdelay + period, initialdelay + 2 * period,... Each execution time of schedulewithfixeddelay is a time interval pushed back from the end of the last task, that is, each execution time is: initialdelay, initialdelay + executetime + delay, initialDelay+2*executeTime+2*delay。 It can be seen that scheduleatfixedrate schedules tasks based on fixed time intervals. Schedulewithfixeddelay schedules tasks based on non fixed time intervals depending on the length of time each task is executed.

Implementation of complex task scheduling with scheduledexecutor and calendar

Timer and scheduledexecutor can only provide task scheduling based on start time and repetition interval, and are not competent for more complex scheduling requirements. For example, set 16:38:10 every Tuesday to perform tasks. Neither timer nor scheduledexecutor can directly implement this function, but we can indirectly implement this function with the help of calendar.

The above code realizes the function of scheduling tasks at 16:38:10 every Tuesday. Its core is to calculate the absolute time of 16:38:10 on the last Tuesday according to the current time, and then calculate the time difference with the current time as a parameter to call the scheduledexceptor function. Java is used to calculate the latest time util. Functions of calendar. First, we need to explain some design ideas of calendar. Calendar has the following combinations to uniquely identify a date:

quote

YEAR + MONTH + DAY_ OF_ MONTH

YEAR + MONTH + WEEK_ OF_ MONTH + DAY_ OF_ WEEK

YEAR + MONTH + DAY_ OF_ WEEK_ IN_ MONTH + DAY_ OF_ WEEK

YEAR + DAY_ OF_ YEAR

YEAR + DAY_ OF_ WEEK + WEEK_ OF_ YEAR

The above combination plus hourofday + minute + second respectively is a complete time identification.

The last combination method is adopted for the above demo. Enter as day_ OF_ Week, second and current date are output as a date that meets the requirements of day_ OF_ Week, second, and the future date closest to the current date. The principle of calculation is from the input day_ OF_ Week starts the comparison. If it is less than the day of the current date_ OF_ Week, you need to report to week_ OF_ Year goes forward, that is, week in the current date_ OF_ Year plus overwrites the old value; If equal to the current day_ OF_ Week, then continue to compare hour_ OF_ DAY; If greater than the current day_ OF_ Week, then directly call Java util. Calendar of calendar The set (field, value) function sets the day of the current date_ OF_ Week, second are assigned as input values, and so on until they are compared to second. We can choose different combinations according to the input requirements to calculate the latest execution time.

Using the above method to realize the task scheduling is cumbersome. It is expected that a more perfect task scheduling tool is needed to solve these complex scheduling problems. Fortunately, the Open Source Toolkit quartz has demonstrated strong capabilities in this regard.

Quartz

OpenSymphony open source organization is another open source project in the field of job scheduling. It can be combined with J2EE and J2SE applications or used alone. Quartz can be used to create simple or complex programs that run ten, a hundred, or even tens of thousands of jobs.

Let's start with an example:

Through the above example: the three most important basic elements of quartz:

• scheduler: scheduler. All scheduling is controlled by it.

• trigger: define trigger conditions. In the example, its type is simpletrigger, which is executed every 1 second (what is simpletrigger will be described in detail below).

• JobDetail & Job: JobDetail defines the task data, and the real execution logic is in the job. In the example, helloquartz. Why is it designed as JobDetail + job instead of directly using job? This is because tasks may be executed concurrently. If the scheduler directly uses jobs, there will be a problem of concurrent access to the same job instance. In JobDetail & job mode, the scheduler will create a new job instance based on JobDetail every time it executes, so as to avoid the problem of concurrent access.

Quartz API

The style of quartz's API is in 2 After X, the DSL style (usually means fluent interface style) is adopted, which is the paragraph of newtrigger () in the example. It is implemented through builder, including the following. (most of the following code will refer to these Builders)

About name and group

Both JobDetail and trigger have name and group.

Name is their unique identifier in the scheduler. If we want to update a JobDetail definition, we only need to set a JobDetail instance with the same name.

Group is an organizational unit. The scheduler will provide some APIs for the operation of the whole group, such as scheduler resumeJobs()。

Trigger

Before you begin to explain each trigger in detail, you need to understand some of the commonalities of triggers.

StartTime & EndTime

The time interval in which the trigger specified by starttime and Endtime will be triggered. Outside this range, trigger will not be triggered. All triggers contain these two attributes.

Priority

When the scheduler is busy, multiple triggers may be triggered at the same time, But resources are insufficient (for example, the thread pool is insufficient). At this time, a better way than scissors and stone cloth is to set the priority. The higher priority will be executed first. It should be noted that the priority will only work between triggers executed at the same time. If one trigger is 9:00 and the other trigger is 9:30. No matter how high the latter priority is, the former will be executed first. The default value of priority is 5. When it is negative, the default value is used. It seems that the maximum value is not specified, but it is recommended to follow the Java standard and use 1-10, otherwise the ghost will know whether there is a larger value above when [priority is 10].

Misfire strategy

When similar schedulers are short of resources, or the machine crashes and restarts, some triggers may not be triggered at the time point when they should be triggered, that is, miss fire. At this time, trigger needs a strategy to deal with this situation. The optional strategies of each trigger are different. Here are two important points to pay attention to:

Misfire trigger has a threshold, which is configured in jobstore. Than RAMJobStore is org quartz. jobStore. misfireThreshold。 Only when this threshold is exceeded will misfire be counted. Less than this threshold, quartz will all be triggered again. All misfire strategies actually answer two questions:

• do you want to re trigger tasks that have misfire?

• if misfire occurs, do you want to adjust the existing scheduling time?

For example, the misfire strategy of simpletrigger includes:

•MISFIRE_ INSTRUCTION_ IGNORE_ MISFIRE_ Policy does not mean to ignore the missed trigger, but to ignore the misfire policy. It will re trigger all misfire tasks when resources are appropriate, and will not affect the existing scheduling time. For example, simpletrigger is executed every 15 seconds, and it is misfire for 5 minutes. A total of 20 are missed. After 5 minutes, assuming that the resources are sufficient and the tasks allow concurrency, it will be triggered at one time. This attribute is applicable to all triggers.

•MISFIRE_ INSTRUCTION_ FIRE_ Now ignores tasks that have misfire and performs scheduling immediately. This usually applies only to tasks that are performed only once.

•MISFIRE_ INSTRUCTION_ RESCHEDULE_ Now_ WITH_ EXISTING_ REPEAT_ Count will set starttime to the current time and immediately reschedule tasks, including misfire.

•MISFIRE_ INSTRUCTION_ RESCHEDULE_ Now_ WITH_ REMAINING_ REPEAT_ Count is similar to misfireinstructionreschedulenowwithexistingrepeat_ Count, the difference is that tasks that have misfire will be ignored.

•MISFIRE_ INSTRUCTION_ RESCHEDULE_ NEXT_ WITH_ EXISTING_ Count restarts scheduling tasks at the next scheduling time point, including misfire.

•MISFIRE_ INSTRUCTION_ RESCHEDULE_ NEXT_ WITH_ REMAINING_ Count is similar to misfire infrastructure next with existingcount, except that tasks that have misfire will be ignored.

•MISFIRE_ INSTRUCTION_ SMART_ This is the default misfire value of all triggers in policy, which roughly means "leaving the processing logic to the smart quartz to decide". The basic strategy is.

• use misfire if scheduling is performed only once_ INSTRUCTION_ FIRE_ Now。

• if the schedule is infinite (repeatcount is infinite), use misfire_ INSTRUCTION_ RESCHEDULE_ NEXT_ WITH_ REMAINING_ COUNT。

• otherwise, use misfire_ INSTRUCTION_ RESCHEDULE_ Now_ WITH_ EXISTING_ REPEAT_ Count misfire is very complicated. You can refer to this article.

Calendar

The calendar here is not the Java of JDK util. Calendar, not to calculate the date. Its function is to supplement trigger's time. Some specific points in time can be excluded or added.

Take "automatic repayment of card debt at 0:00 on the 25th of each month" as an example. We want to exclude the time point of 0:00 on the 25th of February every year (because there is 2.14, it will go bankrupt in February). This time can be realized by calendar.

example:

Quartz kindly provides us with the following calendars. Note that all calendars can be excluded or included, depending on:

•HolidayCalendar。 Specify a specific date, such as 20140613. Accuracy to days.

•DailyCalendar。 Specify the time period (rangestartingtime, rangeendingtime) of each day in the format HH: mm [: SS [: Mmm]]. That is, the maximum accuracy can be up to milliseconds.

•WeeklyCalendar。 Specify the day of the week. Optional values, such as Java util. Calendar. SUNDAY。 The precision is days.

•MonthlyCalendar。 Specify the day of the month. The optional values are 1-31. The precision is days

•AnnualCalendar。 Specify the day of the year. Use as above. The precision is days.

•CronCalendar。 Specifies the cron expression. The precision depends on the cron expression, that is, the maximum precision can be up to seconds.

Trigger implementation class

Quartz has the following trigger implementations:

SimpleTrigger

Specifies a task to be executed at a certain time interval (in milliseconds). It is suitable for tasks similar to starting at 9:00 and executing every 1 hour. Its properties are:

• repeatinterval

• repeatcount the number of repetitions. The actual number of executions is repeatcount + 1. Because it must be executed once at starttime. The following about the repeatcount attribute is the same.

example:

CalendarIntervalTrigger

Similar to simpletrigger, it specifies tasks to be executed at a certain time interval from a certain time. The difference is that the time interval specified by simpletrigger is milliseconds, There is no way to specify every other month (the time interval of each month is not a fixed value), and the interval units supported by calendarintervaltrigger are seconds, minutes, hours, days, months, years and weeks. Compared with simpletrigger, it has two advantages: 1. It is more convenient. For example, you don't have to calculate how many milliseconds an hour equals every hour. 2. It supports intervals that are not of fixed length, such as months and years 。 But the disadvantage is that the accuracy can only reach seconds. It is suitable for tasks similar to starting at 9:00 and executing once a week at 9:00. Its properties are:

• interval execution interval

• intervalunit the unit of execution interval (seconds, minutes, hours, days, months, years, weeks)

example:

DailyTimeIntervalTrigger

Specify a time period of each day to execute tasks at certain intervals. And it can support specified weeks. It is suitable for tasks similar to: specify to execute every 70 seconds from 9:00 to 18:00 every day, and only from Monday to Friday. Its properties are:

• starttimeofday start time of day

• endtimeofday end time of day

• days of week

• interval execution interval

• intervalunit the unit of execution interval (seconds, minutes, hours, days, months, years, weeks)

• repeatcount repetitions

example:

crontrigger

It is suitable for more complex tasks. It supports the syntax of Linux cron (and is more powerful). Basically, it covers most (but not all) of the above three triggers - of course, it is also more difficult to understand. It is suitable for tasks similar to: execute once every day at 0:00, 9:00 and 18:00. Its properties are:

Cron expression

But the expression itself is complex enough. There will be instructions below. example:

Cron expression

• asterisk (): it can be used in all fields to represent each time in the corresponding time domain. For example, in the minute field, it means "every minute";

• question mark (?): this character is only used in the date and week fields. It is usually specified as "meaningless value", which is equivalent to a dotted character;

• minus sign (-): indicates a range. If "10-12" is used in the hour field, it means from 10 to 12 points, i.e. 10,11,12;

• comma (,): indicates a list value. If "Mon, wed, Fri" is used in the week field, it indicates Monday, Wednesday and Friday;

• slash (/): X / Y represents an equal step sequence, where x is the starting value and Y is the incremental step value. If 0 / 15 is used in the minute field, it means 0,15,30 and 45 seconds, while 5 / 15 means 5,20,35,50 in the minute field. You can also use * / y, which is equivalent to 0 / Y;

• L: this character is only used in the date and week fields to represent "last", but it has different meanings in the two fields. L in the date field, it represents the last day of the month, such as the 31st of January and the 28th of February in a non leap year; If l is used in the week, it means Saturday, which is equivalent to 7. However, if l appears in the week field and is preceded by a value x, it means "the last X days of the month". For example, 6L means the last Friday of the month;

• W: this character can only appear in the date field. It is a modification of the leading date and represents the nearest working day from the date. For example, 15W represents the nearest working day from the 15th of the month. If the 15th of the month is Saturday, it matches Friday on the 14th; If the 15th is Sunday, match the 16th Monday; If the 15th is Tuesday, the result is Tuesday the 15th. However, it must be noted that the associated matching date cannot span months. For example, if you specify 1W, if the 1st is Saturday, the result matches Monday, the 3rd, rather than the last day of last month. W string can only specify a single date, not a date range;

• LW combination: LW can be combined in the date field, which means the last working day of the current month; Pound sign (#): this character can only be used in the week field to represent a working day of the current month. For example, 6#3 represents the third Friday of the current month (6 represents Friday, #3 represents the current third), while 4#5 represents the fifth Wednesday of the current month. If there is no fifth Wednesday in the current month, ignore and do not trigger;

• C: this character is only used in the date and week fields and stands for "calendar". It means the date associated with the plan. If the date is not associated, it is equivalent to all the dates in the calendar. For example, 5C in the date field is equivalent to the first day after the 5th day of the calendar. 1c in the week field is equivalent to the first day after Sunday.

Cron expressions are not sensitive to the case of special characters, nor are they sensitive to the case of abbreviations representing weeks. Some examples:

JobDetail & Job

JobDetail is the definition of a task, and job is the execution logic of the task. A job class definition will be referenced in JobDetail. The simplest example:

From the above example, we can see that to define a task, we need to do several things:

• create an org quartz. Job implementation class, and implement its own business logic. For example, donothingjob above.

• define a JobDetail and reference the implementation class

• when you join schedulejob quartz to schedule a task, you will do the following:

•JobClass jobClass=JobDetail. getJobClass()

•Job jobInstance=jobClass. newInstance()。 Therefore, the job implementation class must have a public parameterless construction method.

•jobInstance. execute(JobExecutionContext context)。 Jobexecutioncontext is the context in which the job runs. You can get trigger, scheduler and JobDetail information.

In other words, a new job instance will be created every time scheduling. This has the advantage that when some tasks are executed concurrently, there is no problem of accessing critical resources - of course, if you need to share jobdatamap, there is still a problem of accessing critical resources concurrently.

JobDataMap

Job is an instance of newinstance. How can I pass values to it? For example, I now have two tasks to send e-mail, one to "Lilei" and the other to "hameimei". It can't be said that I want to write two job implementation classes, lileisendemailjob and hanmeimeisendemailjob. The implementation method is through jobdatamap.

Each JobDetail will have a jobdatamap. Jobdatamap is essentially an extension class of map, which only provides some more convenient methods, such as getstring().

We can define JobDetail and add attribute values in two ways:

•newJob(). Usingjobdata ("age", 18) / / add attribute to agejobdatamap

•job. getJobDataMap(). put("name","quertz"); // Add attribute name to jobdatamap

Then you can get the value of this jobdatamap in job in two ways:

For the same JobDetail instance, multiple job instances executing share the same jobdatamap, that is, if you modify the value in the task, it will affect other job instances (concurrent or subsequent).

In addition to JobDetail, trigger also has a jobdatamap, and the shared scope is all job instances that use this trigger.

Job concurrency

Jobs may be executed concurrently. For example, if a task needs to be executed for 10 seconds and the scheduling algorithm is triggered once per second, multiple tasks may be executed concurrently.

Sometimes we don't want the task to be executed concurrently. For example, the task needs to "obtain the list of all unsent messages in the database". If it is executed concurrently, a database lock is required to prevent a data from being processed multiple times. At this time, a @ disallowcurrentexecution is used to solve this problem. That's it:

Note that @ disallowcurrentexecution takes effect on the JobDetail instance, that is, if you define two jobdetails and reference the same job class, they can be executed concurrently.

JobExecutionException

Job. The execute () method is not allowed to throw all exceptions except jobexecutionexception (including runtimeException), so it's best to try catch all Throwables and handle them carefully during coding.

Other properties

• durability If a task is not durable, it will be deleted automatically when there is no trigger associated with it.

• requestsrecovery if a task is "requests recovery", when the running process of the task exits abnormally (such as process crash and machine power failure, but excluding throwing exceptions), quartz will restart the task instance once again.

You can use jobexecutioncontext Isrecovering() queries whether the task is recovered.

Scheduler

• scheduler is quartz's brain, and it is responsible for all tasks.

• schduelr contains two important components: jobstore and ThreadPool.

• jobstore will store runtime information, including trigger, scheduler, JobDetail, business lock, etc. It has a variety of implementations, ramjob (memory implementation), jobstoretx (JDBC, transactions managed by quartz), jobstorecmt (JDBC, using container transactions), clusteredjobstore (cluster Implementation), terracottajobstore (what is terracta).

• ThreadPool is a thread pool. Quartz has its own thread pool implementation. All tasks are executed by the thread pool.

SchedulerFactory

As the name suggests, the scheduler factory is used to create a scheduler. It has two implementations: directschedulerfactory and stdschedulerfactory. The former can be used to customize your own scheduler parameters in the code. The latter is to directly read quartz under classpath Properties (use default values if they do not exist) configuration to instantiate the scheduler. Generally speaking, it is sufficient for us to use stdschulerfactory.

The scheduler factory itself supports the creation of RMI stubs, which can be used to manage remote schedulers. The function is the same as that of the local. You can submit a job remotely. Creation interface of directschedulerfactory:

For configuration examples of stdscheduler factory, please refer to the quartz configuration guide for more configurations:

3、 Quartz integrated spring

To develop a job class, an ordinary Java class, you need to have an execution method:

Put the class into the spring container. You can use configuration or annotation:

Configure JobDetail and specify the job object:

To configure a trigger, you need to specify a cron expression to specify the execution time of the task:

Configure dispatch plant:

The project starts and the timer starts executing.

4、 Analyze the advantages and disadvantages of different scheduled tasks, and find a scheduled task that meets the needs of your project. Timer manages the defects of delayed tasks

In the past, timers were often used in projects, such as cleaning up some garbage files in the project at regular intervals and cleaning up logs at regular intervals; However, timer has some defects, because timer only creates one thread when executing scheduled tasks. Therefore, if there are multiple tasks and the task time is too long, exceeding the interval between the two tasks, some defects will occur

Timer defect when the task throws an exception

If TimerTask throws a runtimeException, timer will stop the running of all tasks

Timer depends on system time when executing periodic tasks

Timer depends on the system time when executing periodic tasks. If the current system time changes, there will be some execution changes. The scheduled executorservice is based on the time delay and will not change due to the change of system time.

Handling of exceptions

An exception is thrown during the execution of a task in quartz, which does not affect the execution of the next task. When the next execution time comes, the timer will execute the task again; TimerTask is different. Once an exception is thrown during the execution of a task, the whole timer life cycle will end and the timer task will never be executed in the future.

Accurate to and function

Quartz creates a new task class object every time it executes a task, while TimerTask uses the same task class object every time. Quartz can be executed at a specific time through cron expressions, while TimerTask cannot. Quartz has all the functions of TimerTask, but TimerTask does not have the above. It basically explains that scheduled executorservice (after JDK1.5) should be used to replace timer in future development.

5、 Cron online expression generator http://cron.qqe2.com/ Appendix cron expression

Cron expressions are used to configure instances of cronrigger. The cron expression actually consists of seven subexpressions. These expressions are separated by spaces.

• seconds

• minutes

• hours

• day of month

• month

• day of week

• year

Example: "0 0 12? * wed" means that it is executed at 12 noon every Wednesday. Individual subexpressions can contain ranges or lists. For example, the wed in the above example can be replaced with "Mon-Fri", "Mon, Fri", or even "mon-wed, sat". Subexpression range:

•Seconds (0~59)

•Minutes (0~59)

•Hours (0~23)

• day of month (1 ~ 31, but note that some months do not have 31 days)

• month (0 ~ 11, or "Jan, Feb, Mar, APR, may, Jun, Jul, Aug, Sep, Oct, Nov, Dec")

• day of week (1 ~ 7,1 = sun or "sun, Mon, Tue, thu, Fri, sat")

•Year (1970~2099)

Format of cron expression: second minute hour day month anniversary (optional).

Field name | allowed values | allowed special characters ---- ---- ---- ---- ---- ---- ---- ---- ---- seconds | 0-59 ----, - * / minutes | 0-59 ----, * / hours | 0-23 ----, * / days | 1-31 ---- */ L W C month | 1-12 or Jan-Dec |, * / day of week | 1-7 or sun-sat |, */ L C # year (optional field) | empty 1970-2099 |, */

Character meaning:

• *: represents all possible values. Therefore, "*" means every month in month, every day in day of month and every hour in hours

• -: indicates the specified range.

•,: indicates that enumeration values are listed. For example, in the minutes subexpression, "5,20" means to trigger in 5 minutes and 20 minutes.

• /: used to specify the increment. For example, in the minutes subexpression, "0 / 15" means to execute every 15 minutes starting from 0 minutes. "3 / 20" means to execute every 20 minutes from the third minute. It has the same meaning as "3,23,43" (indicating the 3rd, 23rd and 43rd minute trigger).

•?: Used in day of month and day of week, it means "no specific value". When one of the two sub expressions is assigned a value, in order to avoid conflict, you need to set the value of the other to ". For example, if you want to trigger scheduling on the 20th of each month, no matter what day of the week the 20th is, you can only use the following expression: 0 0 20 *?, In the end, I thought I could only use "?", Instead of "*".

• L: used in the day of month and day of week strings. It is the abbreviation of the word "last". Its meaning is different in the two sub expressions.

• in day of month, "L" means the last day of a month, January 31 and March 30.

• in day of week, "L" means the last day of the week, that is, "7" or "SAT"

• if there is a specific content before "L", it has other meanings. For example, "6L" means the penultimate day of the month. "FRIL" means the last Friday of the month.

• note: when using the "L" parameter, do not specify the list or range, which will cause problems.

• W: abbreviation of "weekday". Can only be used in the day of month field. Used to describe the working day (Monday to Friday) closest to the specified day. For example, in the day of month field, "15W" refers to the "working day closest to the 15th day of this month" That is, if the 15th day of the month is Saturday, the trigger will be triggered on the 14th day of the month, that is, Friday; If the 15th day of the month is Sunday, the trigger will be triggered on the 16th day of the month, that is, Monday; If the 15th day of the month is Tuesday, it will be triggered on the trigger day. Note: this usage will only calculate the value in the current month and will not exceed the current month. The "W" character can only indicate a day in the day of month and cannot be a range or list. You can also use "LW" to specify the last working day of the month, that is, the last Friday.

• #: can only be used in the day of week field. Used to specify the week ordinal of the month. For example, "6#3" or "fri#3" in the day of week field refers to the third Friday of the month (6 refers to Friday and 3 refers to the third). If the specified date does not exist, the trigger will not be triggered.

Expression example:

0 * * * * ? Triggered every 1 minute

0 0 * * * ? Triggered every 1 hour every day

0 0 10 * * ? Triggered at 10 o'clock every day

0 * 14 * * ? Triggered every 1 minute between 2 p.m. and 2:59 p.m. every day

0 30 9 1 * ? 9:30 am on the 1st of each month

0 15 10 15 * ? Triggered at 10:15 a.m. on the 15th of each month

*/5 * * * * ? Every 5 seconds

0 */1 * * * ? Every 1 minute

0 0 5-15 * * ? Triggered at 5-15 o'clock every day

0 0/3 * * * ? Triggered every three minutes

0 0-5 14 * * ? Triggered every 1 minute between 2 p.m. and 2:05 p.m. every day

0 0/5 14 * * ? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. every day

0 0/5 14,18 * * ? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. and between 6 p.m. and 6:55 p.m

0 0/30 9-17 * * ? Every half an hour during nine to five working hours

0 0 10,14,16 * * ? Every day at 10 a.m., 2 p.m. and 4 p.m

0 0 12 ? * Wed means 12 noon every Wednesday

0 0 17 ? * Tues, Thur, sat every Tuesday, Thursday and Saturday at 5 p.m

0 10,44 14 ? 3 wed is triggered at 2:10 and 2:44 p.m. on Wednesday in March every year

0 15 10 ? * Mon-Fri triggered at 10:15 am from Monday to Friday

0 0 23 L * ? At 23:00 on the last day of each month

0 15 10 L * ? Triggered at 10:15 a.m. on the last day of each month

0 15 10 ? * 6L triggered at 10:15 a.m. on the last Friday of each month

0 15 10 * * ? Triggered at 10:15 a.m. every day in 2005

0 15 10 ? * 6L 2002-2005 triggered at 10:15 a.m. on the last Friday of each month from 2002 to 2005

0 15 10 ? * Triggered at 10:15 am on the third Friday of 6#3 each month

The above timed task (example explanation) in Java implementation of web applications is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>