在项目开发过程中,我们经常需要执行具有周期性的任务。通过定时任务可以很好的帮助我们实现。
1. 添加依赖
<!--定时任务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!--定时任务-->
2. 在启动类中添加注解@EnableScheduling,就可以启用定时任务了
如:
@SpringBootApplication
@EnableScheduling
public class ScheduledemoApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledemoApplication.class, args);
}
}
3. 编写定时任务调度方法
package com.hadwinling.scheduletask;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class Task {
@Scheduled(cron="0/2 * * * * ?")//每2秒执行一次
public void schedule(){
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String currentTime = df.format(time);
System.out.println(currentTime+"===定时任务执行!!!");
}
}
注意:在需要定时任务的方法上加上@Scheduled注解表示该方法将进行调度
其中的属性cron为定时任务的调度时间间隔,本次示例为每2秒调度一次。
cron表达式的写法将在附录给出。
Spring Schedule三种任务调度器分别举例说明。
@Scheduled(cron="0/2 * * * * ?")
Cron表达式由6或7个空格分隔的时间字段组成:
常用的cron 表达式:
给大家一个生成cron表达式网址:http://cron.qqe2.com/
固定间隔任务使用这个注解@Scheduled(fixedDelay = 1000*10)
@Scheduled(fixedDelay = 1000*10): 这个是每次任务结束后10秒执行
固定频率任务@Scheduled(fixedRate = 1000*10)
@Scheduled(fixedRate = 1000*10):表示任务这个是每10秒执行一次
4. 启动SpringBoot,观察控制台输出