目录
package com.test.springboot_schedule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@EnableScheduling
@SpringBootApplication
public class SpringbootScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduleApplication.class, args);
}
// @Scheduled(fixedRate = 30 * 1000)
@Scheduled(cron = "0/30 * * * * ?")
public void saySth() {
System.out.println(Thread.currentThread().getName() + "--say hello world");
}
// @Scheduled(fixedRate = 60 * 1000)
@Scheduled(cron = "0 0/1 * * * ?")
public void doSth() {
System.out.println(Thread.currentThread().getName() + "--do hello world");
}
}
cron表达式总共有七位分别是 秒 分 时 日 月 周 年
但是spring只支持到6位 秒 分 时 日 月 周 不支持年,所以我们如果使用spring写cron表达式的时候只能写6位;
下面说一下cron表达式,如果比较简单的,可以直接在网上找一个在线生成器生成:在线Cron表达式生成器
下面简单说说cron表达式的几个常用符号
, 表示枚举,表示在这几个中的时间才会发生定时 比如:0 20,30 * * * ? 表示每天的每个小时的20分和30分时候回执行定时
- 表示从几顺序到几的时间才会发生定时 比如:0 20-30 * * * ? 表示每天每个小时的20分到30分直接每分钟都会执行定时
/ 表示每隔几个时间才会发生定时 比如:0 0/30 * * * ? 表示每天每个小时每隔30分钟执行定时
* 表示匹配该领域的任务时间值