5 minutes to get to know how to Schedule Tasks in Spring Boot in

This article has been updated to synchronize Github: github.com/Snailclimb/... , welcomed the star.

Many times we need to establish a regular task for the system to help us do something, SpringBoot has helped us to achieve a good, we just need to be directly used, of course you can not SpringBoot comes with regular tasks, the integration of Quartz many time is also a good choice.

This article does not relate to the content SpringBoot integration of Quartz, only demonstrates how to use SpringBoot own realization timing tasks.

Spring Schedule regular tasks to achieve

We only need the most basic items can rely SpringBoot, so there is not posted configuration files.

1. Create a scheduled task

We use the @Scheduledannotation will be able to easily create a scheduled task, the following code covers @Scheduledcommon use, including: fixed-rate execution, fixed-delay execution, initial delay execution, execution timing tasks using Cron expressions.

Cron expression: mainly used for expression that defines the execution time or frequency of execution timing of jobs (scheduled tasks) system is very powerful, you can set the time each day when the task execution, etc., or monthly operating through Cron expression.

Recommend an online Cron Expression Builder: cron.qqe2.com/

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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author shuang.kou
 */
@Component
public class ScheduledTasks {
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * fixedRate:固定速率执行。每5秒执行一次。
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTimeWithFixedRate() {
        log.info("Current Thread : {}", Thread.currentThread().getName());
        log.info("Fixed Rate Task : The time is now {}", dateFormat.format(new Date()));
    }

    /**
     * fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
     */
    @Scheduled(fixedDelay = 2000)
    public void reportCurrentTimeWithFixedDelay() {
        try {
            TimeUnit.SECONDS.sleep(3);
            log.info("Fixed Delay Task : The time is now {}", dateFormat.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * initialDelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
     */
    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void reportCurrentTimeWithInitialDelay() {
        log.info("Fixed Rate Task with Initial Delay : The time is now {}", dateFormat.format(new Date()));
    }

    /**
     * cron:使用Cron表达式。 每分钟的1,2秒运行
     */
    @Scheduled(cron = "1-2 * * * * ? ")
    public void reportCurrentTimeWithCronExpression() {
        log.info("Cron Expression: The time is now {}", dateFormat.format(new Date()));
    }
}

复制代码

About fixedRate In fact, here there is a pit, if we have such a situation: a fixed rate of our method of setting the timer is performed once every 5 seconds. This method is now to perform the following four tasks, time-consuming task of four is: 6 s, 6s, 2s, 3s, ask these tasks by default (single-threaded) how to be executed?

We write a simple program to verify:

    private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTasks.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private List<Integer> index = Arrays.asList(6, 6, 2, 3);
    int i = 0;
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTimeWithFixedRate() {
        if (i == 0) {
            log.info("Start time is {}", dateFormat.format(new Date()));
        }
        if (i < 5) {
            try {
                TimeUnit.SECONDS.sleep(index.get(i));
                log.info("Fixed Rate Task : The time is now {}", dateFormat.format(new Date()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
        }
    }
复制代码

Run the program output is as follows:

Start time is 20:58:33
Fixed Rate Task : The time is now 20:58:39
Fixed Rate Task : The time is now 20:58:45
Fixed Rate Task : The time is now 20:58:47
Fixed Rate Task : The time is now 20:58:51
复制代码

Look at the following diagram of the task run should be well understood.

If we changed this method to run in parallel, the results a different story.

2. Start classes with the @EnableSchedulingcomment

In SpringBoot we only need to add on the startup class @EnableSchedulingcan start the timed task.

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
复制代码

3. custom thread pool to perform scheduled task

By default, the @Scheduledsize of the task in Spring created for the execution of the default thread pool 1, you can by adding the @Scheduledadding the following code in the annotated method to verify.

logger.info("Current Thread : {}", Thread.currentThread().getName());
复制代码

You will find the above code plus the regular tasks of each run will output:

Current Thread : scheduling-1
复制代码

If we need to perform a custom thread pool, then only need to add a new realization of SchedulingConfigurerthe interface configureTasksclass can be, this class need to add @Configurationannotations.

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
    private final int POOL_SIZE = 10;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix("my-scheduled-task-pool-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}
复制代码

Output current thread by way of verification of the above name change.

4. @EnableAsync causes the timing and parallel execution of tasks @Async

If you want your code to be executed in parallel, it can also @EnableAsyncand @ Asynctwo notes to achieve

@Component
@EnableAsync
public class AsyncScheduledTasks {
    private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTasks.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
     */
    //@Async
    @Scheduled(fixedDelay = 2000)
    public void reportCurrentTimeWithFixedDelay() {
        try {
            TimeUnit.SECONDS.sleep(3);
            log.info("Fixed Delay Task : The time is now {}", dateFormat.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

Run the program output is as follows, reportCurrentTimeWithFixedDelay()the method will be performed once every 5 seconds, because we said that the @Scheduledsize of the task in Spring created for the execution of the default thread pool 1.

Current Thread : scheduling-1
Fixed Delay Task : The time is now 14:24:23
Current Thread : scheduling-1
Fixed Delay Task : The time is now 14:24:28
Current Thread : scheduling-1
Fixed Delay Task : The time is now 14:24:33
复制代码

reportCurrentTimeWithFixedDelay()The method of adding @Asyncthe following annotated output, reportCurrentTimeWithFixedDelay()the method will be executed once every 2 seconds.

Current Thread : task-1
Fixed Delay Task : The time is now 14:27:32
Current Thread : task-2
Fixed Delay Task : The time is now 14:27:34
Current Thread : task-3
Fixed Delay Task : The time is now 14:27:36
复制代码

No public

If you want to focus on real-time update of my article and dry sharing, you can focus on my public number.

"Java Interview assault": a document derived specifically for this interview born "Java interview assault" V2.0 PDF version public number backstage reply "Java interview blitz" to receive a free!

Java engineers required Learning Resources: Some Java engineers used public resources to learn numbers background Keywords reply "1" to get free no routine.

My public number

Guess you like

Origin juejin.im/post/5cad53f45188251ace1fe11e