Handle scheduled tasks with Quartz

Handle scheduled tasks with Quartz

In this project, some functions need to be executed regularly. Well, it might be a bit general to say that, let’s make an analogy. For example, when a user logs in, after entering the wrong password three times in a row, the system will freeze the user and no longer allow the user to log in to the system. After midnight, all the frozen users will be unfrozen. The next day you can log in to the system normally. This is for user account security and can effectively prevent brute force password cracking. . . Uh, seems to be digressing, let's get back to the point. Here we only care about how to implement the program to unfreeze users on time every night at midnight.

  For the first time, I thought of the Timer and TimerTask classes that come with JDK, but after testing, it is still difficult to achieve accurate timing. So I looked for other solutions and found Quartz. As for what Quartz is, I think Baidu will tell you. Apart from that, I downloaded the Quartz package and downloaded the latest official version 2.1.7. Then excitedly Baidu got up. There are still quite a lot of articles about the usage of Quartz. However, when Copy came in, it always reported an error. Unfortunately, the latest version of usage is hard to find online. How to do it? My own E text is not good! Hey, E text is my eternal pain, who told me to be patriotic. I looked through the downloaded Quartz package and found that there are many examples in it, and then ran the examples one by one. Ha, hard work pays off, the third example can just solve my current problem, and after careful scrutiny, I found that Quartz is so easy to use. In order to facilitate reuse in the future, and to prevent other friends who have never used Quartz and who are not very good with E-text from being tortured, I decided to record the use of this time.

  The first step: lead the package

  To use Quartz, the following packages must be imported:

  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 included in the downloaded Quartz package, so there is no need to worry about finding these packages.

  Step 2: Create the task class to be executed

  This step is also very simple, just create a class that implements the org.quartz.Job interface, and implement the only method of this interface, execute(JobExecutionContext arg0) throws JobExecutionException. Such as:

Java code copy code Favorite code
  1. import java.text.SimpleDateFormat; 
  2.  
  3. import java.util.Date; 
  4.  
  5. import org.quartz.Job; 
  6. import org.quartz.JobExecutionContext; 
  7. import org.quartz.JobExecutionException; 
  8.  
  9. public class myJob implements Job { 
  10.  
  11.     @Override 
  12.     public void execute(JobExecutionContext arg0) throws JobExecutionException { 
  13.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); 
  14.         System.out.println(sdf.format(new Date())); 
  15.     } 
  16.  
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 needs no explanation.

 

  Step 3: Create a task schedule and execute it

  This step should be the most difficult step, but it is actually very simple, go directly to the code

 

  

Java code copy code Favorite code
  1. import static org.quartz.CronScheduleBuilder.cronSchedule; 
  2. import static org.quartz.JobBuilder.newJob; 
  3. import static org.quartz.TriggerBuilder.newTrigger; 
  4.  
  5. import java.text.SimpleDateFormat; 
  6. import java.util.Date; 
  7.  
  8. import org.quartz.CronTrigger; 
  9. import org.quartz.JobDetail; 
  10. import org.quartz.Scheduler; 
  11. import org.quartz.SchedulerFactory; 
  12. import org.quartz.impl.StdSchedulerFactory; 
  13.  
  14. public class Test { 
  15.     public void go() throws Exception { 
  16.         // First, you must get a reference to the Scheduler 
  17.       SchedulerFactory sf = new StdSchedulerFactory(); 
  18.         Scheduler sched = sf.getScheduler(); 
  19.         //jobs can be called before scheduled's sched.start() method 
  20.          
  21.         //job 1 will be executed every 20 seconds 
  22.         JobDetail job = newJob(myJob.class).withIdentity("job1", "group1").build(); 
  23.         CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build(); 
  24.         Date ft = sched.scheduleJob(job, trigger); 
  25.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); 
  26.         System.out.println(job.getKey() + " has been scheduled to execute on: " + sdf.format(ft) + ", and is repeated with the following repetition rule: " + trigger.getCronExpression()); 
  27.  
  28.         // job 2 will be executed every 2 minutes (at the 15th second of that minute) 
  29.         job = newJob(myJob.class).withIdentity("job2", "group1").build(); 
  30.         trigger = newTrigger().withIdentity("trigger2", "group1").withSchedule(cronSchedule("15 0/2 * * * ?")).build(); 
  31.         ft = sched.scheduleJob(job, trigger); 
  32.        System.out.println(job.getKey() + " has been scheduled to execute on: " + sdf.format(ft) + ", and is repeated with the following repetition rule: "+ trigger.getCronExpression()); 
  33.         
  34.         // Start execution, after the start() method is called, the timer starts to work, and N jobs are allowed to be placed in the timing schedule 
  35.       sched.start(); 
  36.         try { 
  37.             //The main thread waits for one minute 
  38.             Thread.sleep(60L * 1000L); 
  39.         } catch (Exception e) {}     
  40.        //Close timing scheduling, the timer no longer works 
  41.        sched.shutdown(true); 
  42.  
  43.     public static void main(String[] args) throws Exception { 
  44.  
  45.         Test test = new Test(); 
  46.         test.go(); 
  47.     } 
  48.  
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class Test {
    public void go() throws Exception {
        // First, you must get a reference to the Scheduler
      SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        //jobs can be called before scheduled's sched.start() method
        
        //job 1 will be executed every 20 seconds
        JobDetail job = newJob(myJob.class).withIdentity("job1", "group1").build();
        CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build();
        Date ft = sched.scheduleJob(job, trigger);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        System.out.println(job.getKey() + " has been scheduled to execute on: " + sdf.format(ft) + ", and is repeated with the following repetition rule: " + trigger.getCronExpression());

        // job 2 will be executed every 2 minutes (at the 15th second of that minute)
        job = newJob(myJob.class).withIdentity("job2", "group1").build();
        trigger = newTrigger().withIdentity("trigger2", "group1").withSchedule(cronSchedule("15 0/2 * * * ?")).build();
        ft = sched.scheduleJob(job, trigger);
       System.out.println(job.getKey() + " has been scheduled to execute on: " + sdf.format(ft) + ", and is repeated with the following repetition rule: "+ trigger.getCronExpression());
       
        // Start execution, after the start() method is called, the timer starts to work, and N jobs are allowed to be placed in the timing schedule
      sched.start();
        try {
            //The main thread waits for one minute
            Thread.sleep(60L * 1000L);
        } catch (Exception e) {}	
       //Close timing scheduling, the timer no longer works
       sched.shutdown(true);
}

    public static void main(String[] args) throws Exception {

        Test test = new Test();
        test.go();
    }

}

  OK, Job1 and Job2 will be scheduled for scheduled execution. At this point, the program can be executed, but the WARN level log may be output. This is because there is no log4j configuration file, and the configuration file is added, and it is OK. There is only one place that needs to be explained here, and the others can be copied directly into your project. Look at the code:

Java code copy code Favorite code
  1. CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build(); 
CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build();

  What does "0/20 * * * * ?" stand for? This is the key. Understand this, and Quartz can help you solve most of the functions of scheduled tasks. For a detailed explanation, please refer to the following reprint

 

CronTrigger Configuration Format:
Format: [seconds] [minutes] [hours] [days] [months] [weeks] [years]

serial number illustrate Is it required allowed values Wildcards allowed
1 Second Yes 0-59 , - * /
2 Minute Yes 0-59 , - * /
3 Hour Yes 0-23 , - * /
4 day Yes 1-31 , - * ? / L W
5 moon Yes 1-12 or JAN-DEC , - * /
6 week Yes 1-7 or SUN-SAT , - * ? / L #
7 year no empty or 1970-2099 , - * /

Wildcard description: * means all values. For example: setting "*" on the field of minutes means it will be triggered every minute. ? means no value is specified. The use case is that you don't need to care about the value of the current setting of this field. For example: to trigger an operation on the 10th of each month, but don't care about the day of the week, so the field that needs the week position is set to "?" Specifically set to 0 0 0 10 * ? -indicates the interval. For example, setting "10-12" on the hour means that it will be triggered at 10, 11, and 12 o'clock. , means specifying multiple values, for example, setting "MON,WED,FRI" on the week field means triggering on Monday, Wednesday and Friday / for incremental triggering. If "5/15" is set on the second, it starts from 5 seconds and triggers every 15 seconds (5, 20, 35, 50). Set '1/3' on the month field to start on the 1st of each month and trigger every three days. L means the last. On the day field setting, it means the last day of the current month (according to the current month, if it is February, it will also depend on whether it is a leap year [leap]), and on the week field it means Saturday, which is equivalent to "7" or "SAT". If you add a number before "L", it means the last of the data. For example, setting the format "6L" on the week field means "the last Friday of this month" W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上设置"15W",表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 "1W",它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,"W"前只能设置具体的数字,不允许区间"-").

小提示

'L'和 'W'可以一组合使用。如果在日字段上设置"LW",则表示在本月的最后一个工作日触发(一般指发工资 )

# 序号(表示每月的第几个周几),例如在周字段上设置"6#3"表示在每月的第三个周六.注意如果指定"#5",正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了)

小提示

周字段的设置,若使用英文字母是不区分大小写的 MON 与mon相同.

常用示例:

0 0 12 * * ? 每天12点触发
0 15 10 ? * * 每天10点15分触发
0 15 10 * * ? 每天10点15分触发
0 15 10 * * ? * 每天10点15分触发
0 15 10 * * ? 2005 2005年每天10点15分触发
0 * 14 * * ? 每天下午的 2点到2点59分每分触发
0 0/5 14 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发)
0 0/5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) 每天下午的 18点到18点59分(整点开始,每隔5分触发)
0 0-5 14 * * ? Triggers every minute from 2:00pm to 2:05pm every day
0 10,44 14 ? 3 WED Triggered every Wednesday at 2:10pm and 2:44pm in March
0 15 10 ? * MON-FRI Triggered at 10:15 am every day from Monday to Friday
0 15 10 15 * ? Triggered at 10:15 am on the 15th of every month
0 15 10 L * ? Triggered at 10:15 on the last day of the month
0 15 10 ? * 6L Triggered at 10:15 on Friday of the last week of the month
0 15 10 ? * 6L 2002-2005 Triggered at 10:15 on Friday of the last week of every month from 2002 to 2005
0 15 10 ? * 6#3 Triggered on Friday of the third week of the month
0 0 12 1/5 * ? Triggers every 5 days starting from the first noon of the month
0 11 11 11 11 ? Triggered at 11:11 on November 11 every year (Singles Day)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326072178&siteId=291194637