启用springboot 定时任务

在springboot 启动类上增加@EnableScheduling 注解 如下

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableScheduling
public class SpringApplication {
public static void main(String[] args) {
SpringApplication.run(SpringApplication.class, args);
}
}

编写定时逻辑类
1
2
3
4
5
6
7
@Component
public class ScheduledTasks {
@Scheduled(cron = "* * * * * *") //每秒执行一次
public void test(){
System.out.println(new Date());
}
}
@Scheduled() 中时间格式 语法 cron
1
2
3
4
5
6
7
8
9
┌───────────── second (0-59)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of the month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
│ │ │ │ │ ┌───────────── day of the week (0 - 7)
│ │ │ │ │ │ (0 or 7 is Sunday, or MON-SUN)
│ │ │ │ │ │
* * * * * *
测试结果

image.png