条件:
@EnableScheduled@Scheduled关于cron:配置任务执行的时刻,任务开始前,先判断可否执行
,能就执行,否则跳过本次
cron表达式生成:
https://qqe2.com/cron/index
fixedRate:设定上一个任务开始时间到下一个任务的开始时间间隔(如果上一个任务没有完成时,spring会等待上一个任务执行完,并立即执行本次任务)fixedDelay:设定上一个任务结束后间隔多久执行下一个任务创建个springboot项目简单测试一下
启动类:
@SpringBootApplication
@EnableScheduling
public class DemoApiApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApiApplication.class, args);
}
}
定时器:
@Component
@Slf4j
public class TestTask {
@Scheduled(cron ="0/5 * * * * ?")
public void doTask(){
System.out.println("task run.....");
}
}
启动效果:
2022-08-08 14:29:55.595 INFO 19912 --- [ main] com.example.demoapi.DemoApiApplication : Started DemoApiApplication in 1.577 seconds (JVM running for 2.166)
task run.....
task run.....
task run.....
task run.....
spring的定时器默认单线程,任务之间不会并行执行,即便是固定频率,下一次的任务也需要等上一次任务执行完毕,之后再开始。
用途:使任务能异步多线程执行
使用步骤:
测试:
@Scheduled(fixedDelay = 1000)
@Async
public void doTask() throws InterruptedException {
System.out.println("task run.....");
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
}
控制台输出:
2022-08-08 14:57:33.162 INFO 9280 --- [ main] com.example.demoapi.DemoApiApplication : Started DemoApiApplication in 1.646 seconds (JVM running for 2.226)
task run.....
task-1
task run.....
task-2
task run.....
task-3
task run.....
task-4
task run.....
task-5
task run.....
task-6
task run.....
task-7
task run.....
task-8
task run.....
task-1
task run.....
task-2
从上面的打印可以看出:
即使前面的任务还没有完成,定时任务仍以固定的频率开始。而且线程名也不一样,通过多线程来执行。