Spring Framework 分别使用 TaskExecutor 和 TaskScheduler 接口为异步执行和调度任务提供抽象。
To enable support for @Scheduled and @Async annotations add @EnableScheduling and @EnableAsync to one of your @Configuration classes
1
2
3
4
5
|
@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public class TaskExecutorExample {
private class MessagePrinterTask implements Runnable {
private String message;
public MessagePrinterTask(String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
private TaskExecutor taskExecutor;
public TaskExecutorExample(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void printMessages() {
for(int i = 0; i < 25; i++) {
taskExecutor.execute(new MessagePrinterTask("Message" + i));
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Scheduled(fixedDelay=5000)
public void doSomething() {
// something that should execute periodically
}
@Scheduled(fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}
@Scheduled(initialDelay=1000, fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}
|
1
2
3
4
5
6
7
8
|
@Async
void doSomething() {
// this will be executed asynchronously
}
@Async
Future<String> returnSomething(int i) {
// this will be executed asynchronously
}
|
@Async methods may not only declare a regular java.util.concurrent.Future return type but also Spring’s org.springframework.util.concurrent.ListenableFuture or, as of Spring 4.2, JDK 8’s java.util.concurrent.CompletableFuture: for richer interaction with the asynchronous task and for immediate composition with further processing steps.
线程池自动装配类:TaskExecutionAutoConfiguration