takeaway


Due to project requirement, need to use the task to push data regularly, and sometimes need to open multiple tasks to run regularly, behind the timing task under the operating skills, there are two, one is asynchronous (recommended), thread safe, a not asynchronous, not thread-safe, if have a hang up and will affect the output.

use


The premise that

To enable scheduled tasks in a SpringBoot project, add @enablesCheduling to the boot class; otherwise, scheduled tasks will not be available even if the project is started.

Asynchronous scheduled Task

Asynchronous configuration class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/** * Asynchronously enable scheduled task configuration **@date2020/6/24 him * /
@Configuration
@EnableAsync // Enable support for asynchronous events
public class AsyncConfig {

    /** * Number of core threads */
    private int corePoolSize = 20;
    /** * Maximum number of threads */
    private int maxPoolSize = 220;
    /** * Maximum queue length */
    private int queueCapacity = 20;
    /** * The thread pool maintains the free time allowed by threads */
    private int keepAliveSeconds = 20;
    / * * * thread pool tasks (without thread) for processing policy * < p > * rejectedExectutionHandler parameter field is used to configure unique strategy, commonly used rejection policies * < p > * AbortPolicy as follows: Used to be refused to task handler, it will throw RejectedExecutionException * < p > * CallerRunsPolicy: used to be refused to task handler, it directly in the execute method which rejected tasks run in the calling thread. * 

* DiscardOldestPolicy: A handler for a rejected task that abandons the oldest unprocessed request and then retries execute. *

* DiscardPolicy: Handler for rejected tasks, which by default will discard rejected tasks. * /

private ThreadPoolExecutor.AbortPolicy rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy(); @Bean public Executor taskExecutor(a) { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); executor.setRejectedExecutionHandler(rejectedExecutionHandler); executor.initialize(); returnexecutor; }}Copy the code

Starting a Scheduled Task

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/** * Asynchronously enable scheduled task **@date2020/6/24 him * /
@Component
@Async // Start the asynchronous invocation
public class TinfoDemoScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(TinfoDemoScheduleTask.class);


    @Scheduled(cron = "0/1 * * * * *")
    public void scheduled(a) {
        logger.info("Test cron expression, thread name: {}", Thread.currentThread().getName());
    }

    @Scheduled(fixedRate = 1000)
    public void scheduledDemo1(a) {
        logger.info("Test fixedRate, thread name: {}", Thread.currentThread().getName());
    }

    @Scheduled(fixedDelay = 1000)
    public void scheduledDemo2(a) {
        logger.info("Test fixedDelay, thread name: {}", Thread.currentThread().getName()); }}Copy the code

Console

2020-06-24 15:51:17.506  INFO 17092 --- [ taskExecutor-1FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTask: testing, thread name: taskExecutor -1
2020-06-24 15:51:17.506  INFO 17092 --- [ taskExecutor-2FixedDelay] C.L.U.I.D emo. TinfoDemoScheduleTask: testing, thread name: taskExecutor -2
2020-06-24 15:51:18.001  INFO 17092 --- [ taskExecutor-3] C.L.U.I.D emo. TinfoDemoScheduleTask: test the cron expression, thread name: taskExecutor -3
2020-06-24 15:51:18.496  INFO 17092 --- [ taskExecutor-4FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTask: testing, thread name: taskExecutor -4
2020-06-24 15:51:18.500  INFO 17092 --- [ taskExecutor-5FixedDelay] C.L.U.I.D emo. TinfoDemoScheduleTask: testing, thread name: taskExecutor -5
2020-06-24 15:51:19.001  INFO 17092 --- [ taskExecutor-6] C.L.U.I.D emo. TinfoDemoScheduleTask: test the cron expression, thread name: taskExecutor -6
2020-06-24 15:51:19.496  INFO 17092 --- [ taskExecutor-7FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTask: testing, thread name: taskExecutor -7
Copy the code

Non-asynchronous scheduled task

Starting a Scheduled Task

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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


    @Scheduled(cron = "0/1 * * * * *")
    public void scheduled() {
        logger.info("Test cron expression, thread name: {}", Thread.currentThread().getName());
    }

    @Scheduled(fixedRate = 1000)
    public void scheduledDemo1() {
        logger.info("Test fixedRate, thread name: {}", Thread.currentThread().getName());
    }

    @Scheduled(fixedDelay = 1000)
    public void scheduledDemo2() {
        logger.info("Test fixedDelay, thread name: {}", Thread.currentThread().getName()); }}Copy the code

Console

2020-06-24 16:05:32.277  INFO 9400 --- [   scheduling-1FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: testing, thread name: scheduling -1
2020-06-24 16:05:32.282  INFO 9400 --- [   scheduling-1FixedDelay] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: testing, thread name: scheduling -1
2020-06-24 16:05:33.002  INFO 9400 --- [   scheduling-1] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: test the cron expression, thread name: scheduling -1
2020-06-24 16:05:33.276  INFO 9400 --- [   scheduling-1FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: testing, thread name: scheduling -1
2020-06-24 16:05:33.283  INFO 9400 --- [   scheduling-1FixedDelay] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: testing, thread name: scheduling -1
2020-06-24 16:05:34.002  INFO 9400 --- [   scheduling-1] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: test the cron expression, thread name: scheduling -1
2020-06-24 16:05:34.277  INFO 9400 --- [   scheduling-1FixedRate] C.L.U.I.D emo. TinfoDemoScheduleTaskTwo: testing, thread name: scheduling -1
Copy the code

conclusion

It is better to use asynchrony in a project, if one fails, the others will still execute, but if you use non-asynchrony, when one dies, the others will stop executing.

END


chaohen:www.yuque.com/heioky

Do ~