1.启动类上加上如下注解

1
@EnableScheduling

2.配置类配置代码如下:

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
30
31
32
33
34
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;

/**
* <p>
* 定时任务async配置
* </p>
*
* @author: Mr.xiang
* @date: 2019-04-10 13:57
**/
@Configuration
@EnableAsync
public class AsyncConfig {
//最好写到配置文件中,用@Value来获取
private static final int corePoolSize = 10;
private static final int maxPoolSize = 200;
private static final int queueCapacity = 10;

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

}

3.在使用订单订单是任务时,给定时任务执行方法上加@Async 注解,代码示例如下:

1
2
3
4
5
6
7
8
9
10
/**
* 每天凌晨执行一次
*/
@Scheduled(cron = "0 0 0 * * ?")
@Async
public void timeTask(){
log.info("同步中都数据定时任务开始》》》》》》》》》》》》》》》》");
//任务执行体
log.info("同步中都数据定时任务结束《《《《《《《《《《《《《《《《");
}