1. 启动类添加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
2. 在pom.xml里添加定时依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
3. 添加定时任务
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
//定时器1.
//@Scheduled(fixedRate = 1000*60*60)
@Scheduled(fixedDelay = 100)
public void task1(){
for (int i = 0; i < 5; i++) {
System.out.println("task1======" + Thread.currentThread().getName() + ", " + i);
}
}
//定时器2.
@Scheduled(fixedDelay = 100)
//@Scheduled(cron="*/2 * * * * ? ")
public void task2(){
for (int i = 0; i < 5; i++) {
System.out.println("task2====" + Thread.currentThread().getName() + ", " + i);
}
}
}
给类添加@Component,定时任务添加@Scheduled。
定时周期控制可以参考 https://juejin.im/post/5b90dd46f265da0a8c6c02f7
4. 定时任务并发控制
如果需要启动多个定时任务,系统默认是在一个线程里顺序执行,达不到并发高效,可以配置定时多线程(只需一个,多个也只有一个有用)。如下:
@Configuration
public class ScheduleConfig implements SchedulingConfigurer{
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
}
}