Spring6.x annotation support for scheduling and asynchronous execution

Spring provides annotation support for task scheduling and asynchronous method execution.

1 Enable Scheduling annotations

To enable @Scheduledand , add and @Asyncin @Configurationthe class (or in the startup class) , as follows:@EnableScheduling@EnableAsync

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {

}
@SpringBootApplication(exclude = {
		DataSourceAutoConfiguration.class,
})
@EnableScheduling
public class RoadSyncApplication {

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

You can choose relevant annotations for your application. For example, if you only need support @Scheduled, you can omit it @EnableAsync. For more fine-grained control, you can also implement SchedulingConfigurerinterface and AsyncConfigurerinterface separately. See the SchedulingConfigurerand AsyncConfigurerjavadoc for full details.

The recommended mode for default handling @Asyncof annotations is proxythat it only allows calls to be intercepted through a proxy. Local calls within the same class cannot be intercepted using this approach. For more advanced interception modes, consider switching to aspectjmode in conjunction with compile-time weaving or load-time weaving.

2 @Schedulednotes

Annotations and trigger metadata can @Scheduledbe added to methods.

2.1 fixedDelay

The following method is executed every 5000ms, using a fixed delay, that is, the cycle is measured from the [completion time] of each previous call.

@Scheduled(fixedDelay = 5000)  
public void doSomething() {
	// 定期运行的内容  
}

By default, the values ​​for fixed delay, fixed rate, and initial delay will use ms as the time unit. If you want to use different time units, such as s or min, you can @Scheduledconfigure timeUnitthe properties:

@Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS)
public void doSomething() {
}

2.2 fixedRate

For fixed-rate execution, use fixedRatethe attribute. The following method is executed every five seconds (measured from the start time of each call):

@Scheduled(fixedRate = 5, timeUnit = TimeUnit.SECONDS)  
public void doSomething() {

}

For fixed-delay, fixed-rate tasks, you can specify an initial delay by indicating the amount of time to wait before executing the first invocation of the method:

@Scheduled(initialDelay=1000, fixedRate=5000)  
public void doSomething() {
	// 定期运行的内容
}

2.3 One-time tasks

You can just specify an initial delay by indicating the amount of time to wait for the method to execute:

@Scheduled(initialDelay=1000)
public void doSomething() {
	// 只运行一次
}

If a simple periodic schedule is not expressive enough, cron expressions can be used:

@Scheduled(cron="*/5 * * * * MON-FRI")  
public void doSomething() {
	// 仅在工作日运行的内容 
}

You can also use zonethe attribute to specify the time zone in which cron expressions are parsed.

The method to be scheduled must have a void return value and accept no parameters. If a method needs to interact with other objects in the application context, these objects will usually already be injected via dependency injection.

@Scheduledis a repeatable annotation. If several scheduled statements are found on the same method, each statement will be processed independently, firing a separate trigger for each statement. Therefore, such colocalization plans can be overlapped in parallel and executed multiple times in immediate succession. Please make sure that the cron expressions etc. you specify do not accidentally overlap.

@ScheduledStarting with Spring Framework 4.3, methods on beans in any scope are supported . Make sure not to initialize multiple instances of the same annotated class at runtime @Scheduled, unless you really want to dispatch a callback to each such instance.

Make sure not to @Scheduleduse it on bean classes that are annotated and registered in the container as regular Spring beans @Configurable. Otherwise, you will get double initialization (once by the container, once by @Configurablethe aspect), with the result that each @Scheduledmethod is called twice.

FAQ

question

Use the @Scheduled annotation to write scheduled tasks for production, and execute them every 5 minutes:

@Scheduled(cron = "0 0/5 * * * ?")
public void MyTimerJobSchedule() throws Exception {
  //省略具体业务逻辑
  System.out.println("五分钟执行一次");
}

A few days later, the leader informed me that there was a problem. After checking the log, I found that it was a problem with scheduled tasks. It was supposed to run every 5 minutes, but the log found that it was normal from 0 to 3 o'clock every day, but not from 3 to 10 o'clock; it did not continue to run until 10 to 11 o'clock.

reason

It was found that the single-threaded mode of the scheduled task may cause task blocking.

Continue to analyze the log and find that the thread number of the scheduled task is [Scheduling-1]. In addition to executing its own tasks, it also prints the output statements of other scheduled tasks.

Before 3 o'clock every day, the [Scheduling-1] thread is executing a scheduled task that I wrote every 5 minutes. After 3 o'clock, the [Scheduling-1] thread will execute another time-consuming scheduled task until after 10 o'clock, the [Scheduling -1] The thread re-executes the scheduled task every 5 minutes.

It seems that it is indeed because @Scheduled scheduled tasks use single-threaded mode by default: once a scheduled task is time-consuming, it will affect the execution of other scheduled tasks on time.

Solution

Add the @Async annotation to the scheduled task, add the @EnableAsync annotation to the startup class, and use multi-threading mode to execute the scheduled task.

Remarks: Reference URL: https://blog.csdn.net/LYM0721/article/details/89499588

There is a second solution in the reference website, but it has been explained that it is not easy to use, so only the first solution is enough.

This article is published by OpenWrite, a blog that publishes multiple articles !

OpenAI opens ChatGPT to all users for free. Voice programmers tampered with ETC balances and embezzled more than 2.6 million yuan a year. Spring Boot 3.2.0 was officially released. Google employees criticized the big boss after leaving the company. He was deeply involved in the Flutter project and formulated HTML-related standards. Microsoft Copilot Web AI will be Officially launched on December 1st, supporting Chinese Microsoft's open source Terminal Chat Rust Web framework Rocket releases v0.5: supports asynchronous, SSE, WebSockets, etc. The father of Redis implements the Telegram Bot framework using pure C language code . If you are an open source project maintainer, encounter How far can you endure this kind of response? PHP 8.3 GA
{{o.name}}
{{m.name}}

Je suppose que tu aimes

Origine my.oschina.net/u/3494859/blog/10150825
conseillé
Classement