Use quartz to handle scheduled tasks

Source: Internet
Author: User
Tags account security

In this project, a subset of the functions need to be implemented in a timed execution. Well, that might be a little vague, for example. For example, when users log in, the system will freeze the user after 3 consecutive passwords, no longer allow the user to log on to the system, until the night 0 morning, and then thaw for all frozen users, so that users can log on the system the next day. This is done for the user account security, can effectively prevent brute force password ... Well, it seems to be off topic, let's get back to the point. Here we only care how to achieve the 0 morning every night on time to implement the user defrost program.

The first time, I think of the JDK comes with the timer and TimerTask class, can be tested, to achieve accurate timing, or more difficult. Then find another solution, found the quartz, as for quartz is what, I think Baidu will tell you. Apart, download the quartz package, download is the official latest version of 2.1.7. Then the enthusiastic Baidu up, about the use of quartz, the article is still quite a lot of, but, copy came in, always error. Helpless, the latest version of the usage, online and difficult to find. What do we do? My e-text is not good! Ah, E is my eternal pain ah, who call me patriotic it. Flipping through the download of the quartz bag, found there are many examples, and then each run the example. Ha, Kung fu is not a conscientious person, ah, the third example just can solve my problem, and then carefully scrutinize, found quartz so good. In order to facilitate future reuse, but also for other useless quartz and E is not very good friends no longer suffering, decided to use the heart of the record down.

First step: Lead Package

To use quartz, you must introduce these packages:

1, log4j-1.2.16

2, quartz-2.1.7

3, Slf4j-api-1.6.1.jar

4, Slf4j-log4j12-1.6.1.jar

These packages are all in the quartz pack, so there's no need to get headaches for finding these bags.

Step two: Create a task class to be scheduled for execution

This step is also simple, just to create a class that implements the Org.quartz.Job interface, and the only way to implement this interface is execute (jobexecutioncontext arg0) throws Jobexecutionexception can be. Such as:

Import Java.text.SimpleDateFormat;  Import java.util.Date;  Import Org.quartz.Job; Import Org.quartz.JobExecutionContext; Import org.quartz.JobExecutionException;  public class MyJob implements JOB {      @Override public     void execute (jobexecutioncontext arg0) throws jobexecutionexception {         SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss SSS");         System.out.println (Sdf.format (New Date ()));     }  

This example is very simple and does not have to be explained.

Step three: Create a task schedule and execute

This step is one of the hardest steps, but it's actually very simple, directly on the code

1 Import StaticOrg.quartz.CronScheduleBuilder.cronSchedule;2 Import StaticOrg.quartz.JobBuilder.newJob;3 Import StaticOrg.quartz.TriggerBuilder.newTrigger;4  5 ImportJava.text.SimpleDateFormat;6 Importjava.util.Date;7  8 ImportOrg.quartz.CronTrigger;9 ImportOrg.quartz.JobDetail;Ten ImportOrg.quartz.Scheduler; One Importorg.quartz.SchedulerFactory; A Importorg.quartz.impl.StdSchedulerFactory; -   -  Public classTest { the      Public voidGo ()throwsException { -         //First, you must obtain a scheduler reference. -Schedulerfactory SF =Newstdschedulerfactory (); -Scheduler sched =Sf.getscheduler (); +         //jobs can be called before scheduled's Sched.start () method -           +         //Job 1 will be executed every 20 seconds AJobdetail job = Newjob (MyJob.class). Withidentity ("Job1", "group1"). build ();  atCrontrigger trigger = Newtrigger (). Withidentity ("Trigger1", "group1"). Withschedule (Cronschedule ("0/20 * * * * *?")) . Build ();  -Date ft =sched.schedulejob (Job, trigger); -SimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss SSS");  -System.out.println (Job.getkey () + "has been scheduled to execute at:" + sdf.format (ft) + "and repeated with the following repeating rules:" +trigger.getcronexpression ());  -   -         //Job 2 will be executed every 2 minutes (15 seconds in that minute) inJob = Newjob (MyJob.class). Withidentity ("Job2", "group1"). build ();  -Trigger = Newtrigger (). Withidentity ("Trigger2", "group1"). Withschedule (Cronschedule ("15 0/2 * * *?")) . Build ();  toFT =sched.schedulejob (Job, trigger); +System.out.println (Job.getkey () + "has been scheduled to execute at:" + sdf.format (ft) + "and repeated with the following repeating rules:" +trigger.getcronexpression ());  -          the         //start execution, the start () method is called, the timer starts to work, and the timing scheduler allows n jobs to be placed * Sched.start (); $         Try { Panax Notoginseng             //The main thread waits a minute -Thread.Sleep (60L * 1000L);  the}Catch(Exception e) {} +        //turn off scheduled scheduling, timer no longer works ASched.shutdown (true);  the }  +   -      Public Static voidMain (string[] args)throwsException { $   $Test test =NewTest (); - test.go (); -     }  the   -}

K, Job1 and JOB2 will be scheduled to execute on time. At this point the program can be executed, but the warn level log may be output, because there is no log4j configuration file, plus the configuration file, OK. There is only one place to explain here, and the others can be copied directly into your project. Look at the code:

"0/20 * * * *?" What does it mean? This is the key, to understand this, quartz can help you solve most of the functions of scheduled tasks. For detailed explanation, please see the following reprint

Crontrigger Configuration format:
Format: [seconds] [min] [hour] [day] [month] [week] [year]

Serial number Description is required Allowed values to be filled in Allowed wildcard characters
1 Seconds Is 0-59 , - * /
2 Score of Is 0-59 , - * /
3 Hours Is 0-23 , - * /
4 Day Is 1-31 , - * ? /L W
5 Month Is 1-12 or Jan-dec , - * /
6 Week Is 1-7 or Sun-sat , - * ? L
7 Years Whether Empty or 1970-2099 , - * /

A wildcard Description:* Represents all values. For example, setting "*" on a divided field means that every minute will trigger.?Indicates that no value is specified. Use the scene as a value that does not need to be concerned with the current setting of this field. For example: to trigger an action at number 10th per month, but do not care about the weeks, so the field that needs the week position is set to "?" setting to 0 0 0 10 *?-Represents the interval. For example, setting "10-12" on the hour indicates that the 10,11,12 point will be triggered.,Represents specifying multiple values, such as setting "Mon,wed,fri" on the week field to indicate Monday, Wednesday, and Friday triggers/ Used to increment the trigger. If you set "5/15" above the second, the trigger (5,20,35,50) starts at 5 seconds, every 15 seconds. The month field is set to start at ' 1/3 ' as shown in month 1th and is triggered every three days.LIndicate the last meaning. On the day field setting, the last day of the month (according to the current month, if February is also based on whether it is run year [leap]), the week field represents Saturday, which is equivalent to "7" or "SAT". If you precede the "L" with a number, it represents the last of the data. For example, setting the format "6L" On the week field means "last Friday of the month"WRepresents the most recent working day from the specified date (Monday to Friday). For example, set "15W" on the day field, which indicates the most recent day of the month from 15th. If the number 15th is exactly Saturday, then find the most recent Friday (14th) trigger, if 15th is a week, then find the nearest next Monday (16th) trigger. If the number 15th is on the weekday (Monday to Friday), it will be triggered on that day. If the specified format is "1W", it represents the next most recent weekday trigger of 1th per month. If the number 1th is Saturday, it will be triggered by the number 3rd in Monday. (Note that the "W" can only be set to a specific number before the interval "-") is not allowed.

Little Tips

' L ' and ' W ' can be used in a combination. If "LW" is set on the day field, it is triggered on the last business day of the month (usually refers to payroll)

# ordinal (for the number of weeks of the month), for example, setting "6#3" on the Week field is the third Saturday of the month. Note If you specify "#5", which does not happen in the fifth week of Saturday, the configuration will not be triggered (for Mother's Day and Father's Day)

Little Tips

Week field settings, if the use of English letters is case-insensitive mon and Mon are the same.

Common examples:

0 0 12 * *? 12-point trigger per day
0 15 10? * * Triggered 10:15 daily
0 15 10 * *? Triggered 10:15 daily
0 15 10 * *? * Triggered 10:15 daily
0 15 10 * *? 2005 2005 Daily 10:15 Trigger
0 * 14 * *? Every afternoon from 2 to 2:59 per minute.
0 0/5 14 * *? Every afternoon from 2 to 2:59 (the whole point starts, every 5 minutes trigger)
0 0/5 14,18 * *? Every afternoon from 2 to 2:59 (the whole point starts, every 5 minutes trigger) every afternoon from 18 to 18:59 (the hour starts, every 5 minutes trigger)
0 0-5 14 * *? Every afternoon from 2 to 2:05 per minute.
0 10,44 14? 3 WED March minutes 2:10 and 2:44 every Wednesday pm
0 15 10? * Mon-fri Triggered 10:15 every morning from Monday to Friday
0 15 10 15 *? 15th 10:15 A.M. per month, trigger
0 L *? 10:15 trigger on the last day of the month
0 15 10? * 6L Friday 10:15 in the last week of each month
0 15 10? * 6L 2002-2005 Triggered from 2002 to 2005, the last week of Friday, 10:15
0 15 10? * 6#3 Triggered in Friday of the third week of the month
0 0 12 1/5 *? The first noon of each month starts every 5 days
0 11 11 11 11? Every November 11 11:11 trigger (Singles Day)

Use quartz to handle scheduled tasks

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.