1.在启动类上添加 @EnableScheduling 注解,开启定时器
2.设置定时器任务(间隔和cron表达式都行)
package com.example.springboot01.config;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduler {
@Scheduled(fixedRate = 1000) //每2秒执行一次
public void statusCheck() {
System.out.println("【*** A ***】 间隔调度");
}
@Scheduled(cron="* * * * * ?") //每秒调用一次
public void removeToHis() {
try {
//睡眠3秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【*** B ***】cron调度");
}
}
3.配置调度池
package com.example.springboot01.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
/**
* 用于做并行调度使用
*/
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));
}
}