A text read SpringBoot regular tasks

EDITORIAL: From the end of 2018 to start learning SpringBoot, also wrote a number of projects with SpringBoot. This concludes the record about some of the knowledge and learning Springboot. If you are learning SpringBoot, I can focus, learn together and progress together.

The role of regular tasks

As the name suggests is the time to perform regular tasks a method specified. The project is also very common, such as:

  1. Regularly send SMS messages to other users.
  2. Regular statistics.
  3. Weather forecasting system regularly update the data.

In using the timing task SpringBoot

1, create a timer

Create a scheduled task using SpringBoot project is very simple, just a few lines of code to complete. Create a Timer class as a regular task class. code show as below:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration      //主要用于标记配置类,兼备Component的效果。
@EnableScheduling   //开启定时任务
public class Timer {
    //添加定时任务,每隔5秒执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
        System.out.println("当前时间:"+simpleDateFormat.format(new Date()));
    }
}

[Note] which @Scheduled annotation is used to enable regular tasks, the core attributes @ Scheduled annotation is cron, on behalf of the trigger plan expression timed tasks. This expression of the form:

seconds秒,minutes分钟,hours小时,day天,month月,week星期,year年(可选添加)
@Scheduled(cron="seconds minutes hours day month week year")

2, operating results

Process timer task output the current time, the timing for displaying task results. The above method of setting the timer is performed once every 5 seconds, the effect is as follows:
Here Insert Picture Description

3, cron expression

cron expression, the constraint each position is as follows:

No. Explanation Required value Wildcards
1 second Yes 0-59 , - * /
2 Minute Yes 0-59 , - * /
3 hour Yes 0-23 , - * /
4 day Yes 1-31 , - * /
5 month Yes 1-12 , - * / L W
6 week Yes 1-7/SUN-SAT , - * / ? L #
7 year no 1970-2099 , - * /
  1. An asterisk (*): can be used in all fields, represent all the values ​​corresponding to the time domain, for example, when the minute field * indicates "triggers per minute."
  2. Question mark (?): This character is used only date and day of week field, it is usually designated as "meaningless value," the equivalent of a placeholder.
  3. Minus (-): the expression of a range, such as using "10-12" in the hour field, represents from 10 to 12, i.e. 10, 11, 12.
  4. Comma (,): the expression of a list of values, such as the use of "1, 2, 3" in the week field, said Monday, Wednesday and Friday.
  5. Slash (/): x / y expression of a sequence of steps and the like, x is the starting value, y is the increment step value. As used in the field 0 seconds / 15, it is represented as 0, 15, 30 and 45 seconds and 5/15 represents a 5, 20, 35, 50, you can also use * / y min in the field, it is equivalent to at 0 / y.
  6. L: The only character in the day and date fields, representing the "Last" means, but it is a different meaning in both fields. L in the date field, represents the last day, as of January 31, 28 non-leap year the month of February; if L is used in the week, said Saturday, equivalent to 7. However, if L occurs in the week field, and in front of a value X, it said, "The last day of the month X", for example, 6L represents the last Friday of the month.
  7. W: The character can only appear in the date field, a modification of the preamble date indicates the most recent days from that date. For example 15W indicate the nearest working day of the month No. 15, if the number is on Saturday May 15, the Friday match 14; if 15 is a Sunday, the Monday match 16; if the 15th is Tuesday, and that the result is 15 Tuesday numbers. However, care must be taken not able to match the date associated with the plan period, if you specify 1W, if No. 1 is a Saturday, the result of the match is No. 3 on Monday, rather than the last day of last month. W string can only specify a single date, but can not specify a date range.
  8. LW combination: in the date field can be used in combination LW, it means the last working day of the month.
  9. Pound sign (#): This character can only be used in the Days field, indicate the month on a weekday. 6 # 3 as represent the third Friday of the month (Friday 6 represents, # 3 indicates that the current third), and 4 # 5 fifth Wednesday of the month, assuming that there is no fifth Wednesday of the month, do not ignore the trigger.
  10. C: The character used only in the day and date fields, representing the "Calendar" means. It means the date of the associated program, if the date is not associated with, the calendar equivalent of all dates. For example 5C in the date field is equivalent to the first calendar day after the 5th. 1C corresponds to the field of the week Sunday after the first day.

Cron expression parameter values:

  1. Sec (0 to 59), for example, every 5 seconds represents 0/5
  2. Min (0 - 59)
  3. When (0 to 23)
  4. Day day (0 to 31), to be calculated
  5. Month (0 to 11)
  6. Week (can be filled 1-7 [1 for Sunday, 7 for Saturday] or SUN / MON / TUE / WED / THU / FRI / SAT)

Commonly used expression meaning cron

每隔5秒执行一次:0/5 * * * * ? 
每隔1分钟执行一次:0 */1 * * * ? 
每天24点执行一次:0 0 0 * * ? 
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天24点执行一次:0 0 24 L * ? 
每周星期天凌晨1点实行一次:0 0 1 ? * L 
在15分、35分、40分执行一次:0 15,35,40 * * * ?
每天的0点、10点、15点、20点都执行一次:0 0 0,10,15,20 * * ?

4、fixedRate

fixedRate mission interval is twice the starting point of the task, that is, how many milliseconds after the beginning of the implementation of the previous execution.

@Configuration      //主要用于标记配置类,兼备Component的效果。
@EnableScheduling   //开启定时任务
@EnableAsync    //开启多线程
public class Timer {
    @Scheduled(fixedRate  = 3000)
    @Async
    public void configureTasks() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
        System.out.println("开始,时间是 : "+simpleDateFormat.format(new Date())+""+Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结束,时间是 : "+simpleDateFormat.format(new Date())+""+Thread.currentThread().getName());
    }
}

[Note] fixedRate property values in milliseconds, to use as a thread, we need to add on @EnableAsync annotation on the class to open multiple threads. In order to see the effect, after started when the console output, the execution thread to sleep for 5 seconds.
Effect operation (performed in the last three seconds after the start of execution, the output thread distinguished name):
Here Insert Picture Description
As can be seen the first performance, after three seconds, and begin a method, the method is also performed for the first time at this time not end yet.

5, fixedDelay

fixedDelay interval is the beginning and the end of the previous task the next task, which is executed after how many milliseconds after the completion of the previous execution.

@Configuration      //主要用于标记配置类,兼备Component的效果。
@EnableScheduling   //开启定时任务
@EnableAsync    //开启多线程
public class Timer {
    @Scheduled(fixedDelay   = 3000)
    @Async
    public void configureTasks() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
        System.out.println("开始,时间是 : "+simpleDateFormat.format(new Date())+""+Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结束,时间是 : "+simpleDateFormat.format(new Date())+""+Thread.currentThread().getName());
    }
}

[Note] fixedDelay attribute value in milliseconds, after the start of execution when the console output, the execution thread to sleep for 5 seconds.
Operating results (in the last three seconds after the start of the implementation of execution, output thread name to distinguish):
Here Insert Picture Description
It can be seen then after the completion of over three seconds, began to re-execute the first execution.

Finally, what shortcomings, welcome to point out, looking forward to communicate with you.

Published 121 original articles · won praise 368 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_40205116/article/details/104845448