SpringBoot定时任务

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

首先我们要在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表达式讲解比较详细

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值