Thirteen, springboot integrated scheduling tasks (Scheduling Tasks)

Scheduling Tasks

Creating a scheduled task in springboot is relatively simple, just 2 steps:

  • 1. Add the @EnableScheduling annotation to the entry of the program.
  • 2. Add the @Scheduled annotation to the timing method.

1. By default, springboot has already helped us implement timed tasks, and we only need to add corresponding annotations to achieve this.

  spring-boot-starter

2. Startup class enables timing

  Add annotations to the main class of Spring Boot to @EnableSchedulingenable the configuration of timed tasks

@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
public class MemberApplication {

    public static void main(String[] args) {
        SpringApplication.run(MemberApplication.class, args);
    }

}

3. Create a timed task implementation class

Create a timed task that prints the current time on the console every 5s.

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

4. Parameter description

  @Scheduled details

    By adding the @Scheduled annotation to the method, it is indicated that the method is a scheduled task.

    @Scheduled The parameter can accept two kinds of timing settings, one is commonly used, and the other cron="*/6 * * * * ?"is  fixedRate = 6000that both indicate that the content is printed every six seconds

@Scheduled(fixedRate = 5000 ) : Execute again 5 seconds after the last execution time point
@Scheduled(fixedDelay = 5000 ) : Execute again 5 seconds after the last execution time point
@Scheduled(initialDelay =1000, fixedRate=5000 ) : Execute after the first delay of 1 second, and then execute every 5 seconds according to the rules of fixedRate
@Scheduled(cron ="*/5 * * * * *") : define rules via cron expressions

Reference: Scheduling Tasks

Guess you like

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