Spring Boot整合定時任務Task,一秒搞定定時任務

前面介紹了Spring Boot 中的整合Redis緩存已經如何實現數據緩存功能。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。

今天主要講解Springboot整合定時任務。在SpringMvc中也會用到很多的定時任務,主要是通過Quartz實現。但是在Spring MVC中使用這些插件相對還是比較麻煩的:要增加一些依賴包,然後加入各種配置等等。Spring Boot相對就簡單很多了,現在就來說說Spring Boot 是怎麼實現定時任務的。


一、使用註解@EnableScheduling

在application啟動類中,加上@EnableScheduling 註解,Spring Boot 會自動掃描任務類,開啟定時任務。

<code>package com.weiz;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;


@SpringBootApplication
//掃描 mybatis mapper 包路徑
@MapperScan(basePackages = "com.weiz.mapper")
//掃描 所有需要的包, 包含一些自用的工具類包 所在的路徑
@ComponentScan(basePackages = {"com.weiz","org.n3r.idworker"})
//開啟定時任務
@EnableScheduling
public class SpringBootStarterApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootStarterApplication.class, args);
}

}/<code>

說明:

1、@EnableScheduling 為開啟定時任務。

2、@ComponentScan 定義掃描包的路徑。


二、創建任務類,定義@Component 組件

創建com.weiz.tasks包,在tasks包裡增加TestTask任務類,加上@Component 註解,那麼TestTask就會作為組件被容器掃描到。掃描到之後Spring Boot容器就會根據任務類裡面定義的時間,定時執行了。

<code>package com.weiz.tasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestTask {

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

// 定義每過3秒執行任務
@Scheduled(fixedRate = 3000)
// @Scheduled(cron = "4-40 * * * * ?")
public void reportCurrentTime() {
System.out.println("現在時間:" + dateFormat.format(new Date()));
}
}/<code>

說明:@Scheduled 是定時任務執行的時間,可以每個一段時間執行,也可以使用cron 表達式定義執行時間。


三、Cron表達式

Spring Boot 定時任務支持每個一段時間執行或是使用cron 表達式定義執行時間。關於cron表達式,我之前的文章介紹過,大家可以看我以前的文章:《Quartz.NET總結(二)CronTrigger和Cron表達式》


四、測試

啟動程序之後,就可以看到系統每隔3s,會打印系統時間。

Spring Boot整合定時任務Task,一秒搞定定時任務


最後

以上,就把Spring Boot整合定時任務簡單介紹完了,是不是特別簡單,下一篇我會介紹Spring boot 的異步任務。



分享到:


相關文章: