在咱们的项目开发过程当中,常常须要定时任务来帮助咱们来作一些内容,springboot默认已经帮咱们实行了,只须要添加相应的注解就能够实现java
pom包里面只须要引入springboot starter包便可git
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>复制代码
在启动类上面加上@EnableScheduling
便可开启定时github
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}复制代码
定时任务1:spring
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}复制代码
定时任务2:springboot
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("如今时间:" + dateFormat.format(new Date()));
}
}复制代码
结果以下:spring-boot
this is scheduler task runing 0
如今时间:09:44:17
this is scheduler task runing 1
如今时间:09:44:23
this is scheduler task runing 2
如今时间:09:44:29
this is scheduler task runing 3
如今时间:09:44:35复制代码
@Scheduled
参数能够接受两种定时的设置,一种是咱们经常使用的cron="*/6 * * * * ?"
,一种是 fixedRate = 6000
,两种都表示每隔六秒打印一下内容。this
fixedRate 说明spa
@Scheduled(fixedRate = 6000)
:上一次开始执行时间点以后6秒再执行@Scheduled(fixedDelay = 6000)
:上一次执行完毕时间点以后6秒再执行@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延迟1秒后执行,以后按fixedRate的规则每6秒执行一次示例代码code
喜欢个人文章,请关注个人公众号orm