SpringBoot定时任务

来源:互联网 发布:绝地游戏画面优化 编辑:程序博客网 时间:2024/05/18 10:33

定时任务是一个后台经常要用到的功能

首先我们要在SpringBoot里配置pom.xml文件

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

只要有starter就好了(spring-boot-starter-xxx也行)

创建一个定时任务

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Created by cw on 2017/7/20.
*/
@Component
public class SchedulerTaskFindAndSend {
private int count=0;
@Scheduled(cron="*/30 * * * * ?")
private void process(){
System.out.println("count = "+(count++));
}
}

在@SpringBootApplication下添加@EnableScheduling

1
2
@SpringBootApplication
@EnableScheduling

启动运行程序
控制台会每隔30秒打印出 count = 计数

关于@Scheduled

除了cron=” “ 这种方式外
还有以下几种

  • @Scheduled(fixedRate = 3000) ————————上一次开始执行时间点之后3秒再执行
  • @Scheduled(fixedDelay = 3000) ————————上一次执行完毕时间点之后3秒再执行
  • @Scheduled(initialDelay=1000, initialDelay = 3000) ————————第一次延迟1秒后执行,之后按fixedRate的规则每3秒执行一次

关于cron表达式
可以看下这篇博客对于cron表达式讲解比较详细