直接上代碼:
1、定義一個配置類
import org.springframework.beans.factory.annotation.Value;
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;
@Configuration
@EnableAsync
public class ScheduleConfig {
@Value("${schedule.corePoolSize}") // 引入yml配置
private int corePoolSize;
@Value("${schedule.maxPoolSize}")
private int maxPoolSize;
@Value("${schedule.queueCapacity}")
private int queueCapacity;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
application.yml
schedule: corePoolSize: 10 maxPoolSize: 100 queueCapacity: 10
2、定義需要按時執行的服務
corn語句在線生成器:http://cron.qqe2.com/
說明:可能會遇到定時任務一下次執行多次的情況,這是由於執行速度很快,corn語句匹配仍然生效導致的。需要修改corn語句,使其精確匹配,比如在秒位置寫入0就是這個目的。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
public class ScheduleService {
// 每10分鍾調用一次
@Scheduled(cron = "0 0/10 * * * ?") // corn語句
@Async
public void s1() {
// 服務1
}
// 每天4點調用一次
@Scheduled(cron = "0 0 4 * * ?")
@Async
public void s2() {
// 服務2
}
}
