创建 springboot 项目 springboot_task

pom 文件添加依赖

1
2
3
4
5
6
<!-- 添加 Scheduled 坐标 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

主程序添加注解

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableScheduling
public class SpringbootTaskApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}

创建 Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class TaskController {
/**
* @return void
* @Scheduled:定时规则 cron:,项目启动后每5秒执行一次
* <p>
* fixedDelay:距离上一次定时任务执行完毕后N毫秒在执行,
* 执行A任务花了5秒,比如参数是3000,A任务执行完成之后,在过3秒执行
* <p>
* fixedRate:执行周期,执行频率,
* 定时任务执行开始,在过N毫秒后执行,
* 执行A任务花了2秒,比如参数是3000,A任务执行完成之后,在过1秒后执行,
* 执行A任务花了15秒,比如参数是3000,A任务执行完成之后,立即执行。
* @auther
*/
@Scheduled(fixedDelay = 3000)
public void myTask() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(new Date()));
}
}

修改程序 ,换成 cron 参数

关于cron表达式:点我查看

1
2
3
4
5
6
// 每隔10秒执行一次
@Scheduled(cron = "0/10 * * * *")
public void myTask() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(new Date()));
}

运行主程序,查看效果

总结

1、注解

定时任务在配置类上添加@EnableScheduling开启对定时任务的支持

在相应的任务的类上添加@Component

在相应的方法上添加@Scheduled声明需要执行的定时任务

2、参数

@Scheduled 注解中有以下几个参数

cron
zone
fixedDelay 和 fixedDelayString
fixedRate 和 fixedRateString
initialDelay 和 initialDelayString

  1. cron 是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次

  2. zone 表示执行时间的时区

  3. fixedDelay 和 fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

  4. fixedRate 和 fixedRateString 表示一个固定频率执行,上个任务开始后,多长时间后开始执行

  5. initialDelay 和 initialDelayString 表示一个初始延迟时间,第一次被调用前延迟的时间