前言:
创建一个spring boot项目,引入spring-boot-starter-web依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
方式一:使用注解
1. 在启动类上添加 @EnableScheduling 注解,表示开启定时任务。
2.在方法上使用 @Scheduled 注解表示开启一个定时任务:下面参数单位都是毫秒
- fixedRate:表示按一定频率来执行定时任务,具体是指两次任务的开始时间间隔,即第二次任务开始时,第一次任务可能还没结束。
@Configuration
@EnableScheduling //开启定时任务
public class ScheduleTask1 {
//每3秒执行一次
@Scheduled(fixedDelay = 3000)
private void myTasks() {
System.out.println("I do myself per third seconds");
}
}
- fixedDelay:表示按一定时间间隔来执行定时任务,具体是指本次任务结束到下次任务开始之间的时间间隔。该属性还可以配合initialDelay使用, 定义该任务延迟执行时间。
- initialDelay:表示首次任务启动的延迟时间。与fixedDelay配合使用。
@Component
@EnableScheduling //开启定时任务
public class ScheduleTask {
//容器启动后,延迟10秒后再执行一次定时器,以后每10秒再执行一次该定时器。
@Scheduled(initialDelay = 10000, fixedRate = 10000)
private void myTasks3() {
System.out.println("我是一个定时任务3");
}
}
- cron:通过 cron 表达式来配置任务执行时间,cron 表达式格式为:[秒] [分] [小时] [日] [月] [周] [年]
这个不需要刻意记,可以使用网页的自动生成,可以自己指定年月日分秒....
https://cron.qqe2.com/
这里演示一个,每5s,10s,15s执行一次
@Component
@EnableScheduling
public class JOB {
@Scheduled(cron = "5,10,15 * * * * ?")
public void run(){
System.out.println("我执行了");
}
}
运行结果:
注意:类名需要加上@Component注解,交给springboot去管理