There are several ways to realize traditional scheduled task:

Timer: This is the java.util.Timer class that comes with Java. This class allows you to schedule a java.util.TimerTask. This allows your program to run at a certain frequency, but not at a specified time. Generally used less. ScheduledExecutorService: also a JDK class; Is a scheduled task class based on thread pool design, each scheduled task will be assigned to a thread in the thread pool to execute, that is, the task is concurrent execution, do not affect each other. Spring Task: The Task that comes with Spring3.0 can be thought of as a lightweight Quartz and is much simpler to use. Quartz: This is a powerful scheduler that allows your program to execute at a specified time or at a certain frequency. Configuration is a bit complicated.Copy the code

In the SpringBoot project, it is very easy to implement Scheduled tasks using annotations (@scheduled)

Start with the @Scheduled annotation

@scheduled accepts two kinds of timing Settings: the first is cornexpression. One is the Rate/Delay expression (millisecond value) : @scheduled (fixedRate = 6000) : The value is executed every 6 seconds since the last execution point in time. @scheduled (fixedDelay = 6000) : Scheduled is executed 6 seconds after the last time point. @Scheduled(initialDelay=1000, fixedRate=6000) : Scheduled(initialDelay=1000, fixedRate=6000) : Executed after the first delay of 1 second and then every 6 seconds according to fixedRate's rules. Note: * represents all values and in minutes represents each minute triggered. In hours, dates, months, etc., it means every hour, day, month. ? Indicates that no value is specified. Indicates that you do not care about the value set at the current location. For example, if you don't care about the day of the week, fill in the position of the week? .     The main reason is that the date and week are repeated so one of them must be set to? - Indicates an interval. If the hour is set to 10-12, the clock is triggered at 10,11 and 12. Represents multiple values. Hours are set to 10,12 to trigger at 10 and 12. / indicates incremental triggering. 5/15 indicates that the trigger is triggered every 15 seconds starting from the fifth second. L for the last meaning. Day indicates the last day. Sunday means Saturday or 7. L is preceded by data, indicating the last of the data. Set 6L on Monday to indicate the last Friday. 6 indicates Friday. W indicates the working day closest to the specified date. Trigger on the working day closest to 15th of the month.# indicates the day of the month. 6#3 is the third Friday of the month.Example:"0, 0, 12 * *?It's triggered every day at 12 noon"0 15 10? * *"Triggered every day at 10:15 a.m"0, 15, 10 * *?"Triggered every day at 10:15 a.m"0, 15, 10 * *? *"Triggered every day at 10:15 a.m"0, 15, 10 * *? 2005"In 2005, it was triggered every day at 10:15 a.m"0 * 14 * *?"Triggered every minute between 2 p.m. and 2:59 p.m. each day"0 0/5 14 * *?"Triggered every 5 minutes between 2 p.m. and 2:55 p.m. each day"0/5 14,18 * *?"Triggered every 5 minutes between 2 p.m. and 2:55 p.m. and 6 p.m. and 6:55 p.m. each day"0 0-5 14 * *?"Triggered every minute between 2 p.m. and 2:05 p.m. each day"0 10 44 14? 3 WED"Triggered at 2:10 PM and 2:44 PM on Wednesdays of March each year"0 15 10? * MON-FRI"Triggered Monday through Friday at 10:15 a.m"0, 15, 10, 15 times?"Triggered at 10:15 am on the 15th of each month"0 15 10 L * ?"Triggered at 10:15 a.m. on the last day of each month"0 15 10? * 6L"Triggered at 10:15 am on the last Friday of every month"0 15 10? * 6L 2002-2005"Triggered on the last Friday of each month from 2002 to 2005 at 10:15 am"0 15 10? * 6 # 3"Third Friday of every month 10:15 am trigger every day 6:06 * * * every two hours 0 */2 * * * between 11:00 PM and 8:00 am every two hours, 8:023-7/2, 8 * * * the 4th of each month and every Week Monday to Wednesday 11:011 4 * 1-3 January 1st 4:041 1 *Copy the code

Online Cron expression generator: cron.qqe2.com/

Enable support for scheduled tasks with the @enablesCheduling annotation on the main class

@Component
public class ScheduledTest {
    private static Logger logger = LoggerFactory.getLogger(ScheduledTest.class);

    @Scheduled(cron = "0/5 * * * * *")
    public void scheduled(){
        logger.info("= = = = = > > > > > cron execution - {}",DateUtils.getCurrentDateMillTime());
    }
    @Scheduled(fixedRate = 5000)
    public void scheduled1() {
        logger.info("= = = = = > > > > > fixedRate execution - {}", DateUtils.getCurrentDateMillTime());
    }
    @Scheduled(fixedDelay = 5000)
    public void scheduled2() {
        logger.info("= = = = = > > > > > fixedDelay execution - {}",DateUtils.getCurrentDateMillTime()); }}Copy the code

After the project is restarted, tasks are executed in the background at an interval of 5 seconds

If there is only one scheduled task, this is no problem. When the number of scheduled tasks increases, if one task is blocked, other tasks cannot be executed. At this time, multithreading is required

Create AsyncConfig class:

@configuration @enableasync // EnableAsync support public class AsyncConfig {@value ("${corePoolSize}")
    private int corePoolSize;

    @Value("${maxPoolSize}")
    private int maxPoolSize;

    @Value("${queueCapacity}")
    private int queueCapacity;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        returnexecutor; }}Copy the code

Corresponding configuration file:

Configure scheduled tasks
corePoolSize: 10
maxPoolSize: 200
queueCapacity: 10
Copy the code

Finally, add @async to the class or method of the scheduled task. Finally, restart the project, and each task is in a different thread without affecting each other