1. Use the Schedule function

To use the Schedule function, add the @enablesCheduling annotation to the * application. Java file in SpringBoot

@EnableScheduling @SpringBootApplication public class ScheduleApplication { public static void main(String[] args) { SpringApplication.run(ScheduleApplication.class, args); }}Copy the code


2. To create a Service

Create com. Example. The schedule. The service package, and then create TaskService interface classes

package com.example.schedule.service;

public interface TaskService {

    void sayHello(String type);
}Copy the code

Create a service interface implementation package com. Example. Schedule. Service. Impl, then create TaskService TaskServiceImpl implementation class

package com.example.schedule.service.impl;

import com.example.schedule.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

public class TaskServiceImpl implements TaskService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

  public void sayHello(String type) {
        try {
            long startTime = System.currentTimeMillis() / 1000;
            logger.info(type + "= >" + startTime + "- Mission begin.");

            logger.info(type + "= >" + "Mission in progress.");


            long endTime = System.currentTimeMillis() / 1000;
            logger.info(type + "= >" + endTime + "- Mission terminated."); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

3. Get to the point

Create the task package com.example.schedule.job and then create the main scheduled task implementation class ScheduleJob within the package

package com.example.schedule.job; import com.example.schedule.service.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduleJob { @Autowired private TaskService taskService; . Implementation of scheduled tasks}Copy the code

With @scheduled Scheduled tasks, the rules to follow are:

  • The return value of this method should bevoid
  • The method argument should be null

3.1. Using fixedDelay scheduled Tasks

@Scheduled(fixedDelay = 2000)
public void fixedRateTask() {
Copy the code

When a scheduled task is implemented with fixedDelay, the period between end of last task and start of next task lasts a fixed 2000 ms, or 2 seconds.

Quests always wait two seconds after the last one.

In addition to using fixedDelay, you can use fixedDelayString to do the same.

@Scheduled(fixedDelayString = "2000")
public void fixedDelayStringTask() {
Copy the code

3.2. Use fixedRate to schedule tasks

@Scheduled(fixedRate = 2000)
public void fixedRateTask() {
Copy the code

When a scheduled task is implemented using fixedRate, a fixed 2000 milliseconds or 2 seconds elapsed between the start of last Task and the start of next task.

Instead of waiting for the last mission to end, the next mission will start 2 seconds after the start of the mission.

Like fixedDelay, fixedRate can also be implemented using fixedRateString.

@Scheduled(fixedRateString = "2000")
public void fixedRateStringTask() {
Copy the code

3.3. Use initialDelay together

@Scheduled(initialDelay = 1000, fixedDelay = 2000)
public void fixedDelayWithInitialDelayTask() {
}Copy the code

When a scheduled task has initialDelay set, the task will not execute immediately upon loading and will wait for the initialDelay value to start its first execution, which will then continue to execute periodically according to fixedDelay.

It is also possible to replace fixedDelay with fixedRate, again waiting for the initialDelay value to start the first execution, although it will continue to execute periodically according to fixedRate. But at the same time set up fixedDelay and fixedRate so will quote us org. Springframework. Beans. Factory. BeanCreationException error.

3.4. Using crON scheduled Tasks

Compared with fixedDelay and fixedRate, the cron expression can control the execution of tasks more flexibly.

@Scheduled(cron = "*/5 * * * * *")
public void cronTask() {
}Copy the code

This is equivalent to @scheduled (fixedDelay = 5000) which is waiting 5 seconds after the last task has been executed.

Cron expressions have special syntax. Here are some commonly used syntax for reference. Use the CORN expression generator to generate complex syntax, or learn the corn syntax.

Cron has 7 bits in total, but the last bit is year, so we can leave it blank, so we can write 6 bits:

  • The first digit is seconds. The value ranges from 0 to 59
  • The second value is the minute, ranging from 0 to 59
  • The third digit indicates the hour. The value ranges from 0 to 23
  • The fourth digit is day/day. The value ranges from 1 to 31
  • The fifth digit is the date and month. The value ranges from 1 to 12
  • Sixth place, week, value 1-7, Monday, Tuesday… Week 1, week 2, Week 1, Week 2, Week 1, Week 2, Week 1, Week 2, Week 2
  • The seventh digit, the year, can be left blank, 1970-2099

There are also some special symbols in cron that have the following meanings:

● (*) asterisk: can be understood to mean every second, every minute, every day, every month, every year…

Low (?) Question mark: The question mark can only appear in the two positions of date and week, indicating that the value of this position is uncertain. It is executed at 3 o ‘clock every day, so the position of the sixth week, which we do not need to pay attention to, is an uncertain value. Also: Date and week are mutually exclusive elements, indicated by a question mark without specifying a value. For example, January 10, say Monday, would be inconsistent if the location of the week was designated Tuesday.

● (-) minus sign: expresses a range. For example, if “10-12” is used in the hour field, the range is from 10 to 12, that is, 10,11,12

● (,) comma: indicates a list value. If “1,2,4” is used in the week field, it indicates Monday, Tuesday, and Thursday

● (/) slash: such as: x/y, x is the starting value, y is the step size, such as the first (seconds) 0/15 is, starting from 0 seconds, every 15 seconds, the last is 0, 15, 30, 45, 60 and: */y, equal to 0/y

Here are a few examples for you to verify:

  • 0, 0, 3 * *? Every day at 3 o ‘clock
  • 0, 5, 3 * *, right? Every day at 3:05
  • 0 5 3? * * is executed at 3:05 every day, the same as above
  • 0 5/10, 3 times * *, right? Every day at 3:5, 15, 25, 35, 45, 55
  • 0 to 10 3? * 1 Sunday is executed at 3:10 every week. Note: 1 indicates Sunday
  • 0 to 10 3? * 1 #3 The third week of each month, executed on Sunday, # can only appear in the week position

4. To summarize

  • The fixedDelay property ensures that there is a fixed time interval between the end time of a task and the start time of the next task.
  • The fixedRate property runs the task every n milliseconds. > Use the fixedDelay property when you need to ensure that only one task instance is running; Use the fixedRate attribute when the tasks are performed independently.