项目中很多时候会使用到定时任务,这篇文章介绍一下springboot整合定时任务。
springboot整合定时任务其实就两点,
1.创建一个能被定时任务类,方法上加入@Scheduled注解
2.在启动类application上加入@EnableScheduling注解
代码如下,pom文件我只加入了devtools,其实不加入也可以
4.0.0 com.dalaoyang springboot_scheduled0.0.1-SNAPSHOT jar springboot_scheduled springboot_scheduled org.springframework.boot spring-boot-starter-parent1.5.9.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-devtoolsruntime org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
application类代码如下:
package com.dalaoyang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}定时任务类TestTimer
package com.dalaoyang.timer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class TestTimer {
@Scheduled(cron = "0/1 * * * * ?")
private void test() {
System.out.println("执行定时任务的时间是:"+new Date());
}
}到这里启动项目,可以看到控制台如下
需要注意的是@Scheduled(cron = “0/1 * * * * ?”)中cron的值根据自己实际需要去写,如果需要可以去下面的网站去弄。
http://cron.qqe2.com/



