Scheduled tasks usually exist in medium and large enterprise projects. In order to reduce the pressure on servers and databases, some business logic is completed in time. SpringBoot has timed tasks built in for us, and all we need is a note to turn the timing on for us.

Enable the timing function with @enablesCheduling and @scheduled

@Scheduled

  • Function: Spring timer (execute a piece of code periodically or poll a piece of code periodically)
  • Usage scenarios: Annotations on methods

@EnableScheduling

  • Enable the Spring timer function.

Timer parameter writing method

Timer parameters can be written in cron expressions or directly configured with fixedDelay and fixedRate parameters

The first configuration mode

Methods do not execute after a project is started, but wait until the execution cycle is up

@Scheduled(cron = "0/5 * * * * ?" ) public void execute() { log.info("ScheduleTask "+ Thread.currentThread().getName()); }Copy the code

Second parameter mode

Execute the project as soon as it is successfully started

@Scheduled(fixedRateString="1000")
public void execute() {
    log.info("ScheduleTask "+ Thread.currentThread().getName());
}
Copy the code

Scheduled selection order for thread pools

Instead of manually creating threads ourselves in projects, methods are executed through a common thread pool to avoid resource exhaustion in multi-person teams due to custom threads. Before customizing thread pools, you should first understand how Spring selects thread pools when executing asynchronous tasks or methods.

The Scheduled selection order for thread pools is shown below:When Spring executes a scheduled task, it first looks for a bean of type TaskScheduler or name TaskScheduler in the context. If it cannot find one, it manually creates a thread to execute the task.

The following figure defines two thread pools of the same type, except for the name of the bean

The unit test code is as follows:

package com.mty.jls.scheduleTest; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author jiangpeng * @date 2021/1/1514:55 */ @SpringBootTest( classes = {TaskSchedulerPool.class, AsyncApplicationTests.TestConfig.class} ) @Slf4j @RunWith(SpringJUnit4ClassRunner.class) public class AsyncApplicationTests { @Test public void testCron() { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } @Configuration @EnableScheduling public static class TestConfig { @Bean public ScheduleTask getScheduleTask() { return new ScheduleTask(); } @Bean public ScheduleTask2 getScheduleTask2() { return new ScheduleTask2(); } } @Component static class ScheduleTask { @Scheduled(fixedRateString="1000") public void execute() { log.info("ScheduleTask "+ Thread.currentThread().getName()); } } @Component static class ScheduleTask2 { @Scheduled(fixedRateString="2000") public void execute() { log.info("ScheduleTask 2 "+ Thread.currentThread().getName()); }}}Copy the code

The execution result is shown as follows:

Pay attention and don’t get lost

The article continues to update every week, you can wechat search “ten minutes to learn programming” the first time to read and urge more, if this article is written well, feel something ~ for praise 👍 for attention ❤️ for share ❤️ everyone’s support and recognition, is the biggest power of my creation, we see the next article!