在咱們的項目開發過程當中,常常須要定時任務來幫助咱們來作一些內容,springboot默認已經幫咱們實行了,只須要添加相應的註解就能夠實現spring
pom包裏面只須要引入springboot starter包便可springboot
<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
便可開啓定時spring-boot
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
定時任務1:this
@Component public class SchedulerTask { private int count=0; @Scheduled(cron="*/6 * * * * ?") private void process(){ System.out.println("this is scheduler task runing "+(count++)); } }
定時任務2:spa
@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())); } }
結果以下:code
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
,兩種都表示每隔六秒打印一下內容。orm
fixedRate 說明ci
@Scheduled(fixedRate = 6000)
:上一次開始執行時間點以後6秒再執行@Scheduled(fixedDelay = 6000)
:上一次執行完畢時間點以後6秒再執行@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延遲1秒後執行,以後按fixedRate的規則每6秒執行一次