spring進階教程(三):定時任務

前言

前幾節(jié)我們用第三方框架quarz實現(xiàn)了定時任務,實際上spring3.1開始,spring已經(jīng)內(nèi)置了定時任務的支持,實現(xiàn)非常簡單,下面我們一起看看怎么實現(xiàn)

參考項目:https://github.com/bigbeef/cppba-sample
開源地址:https://github.com/bigbeef
個人博客:http://blog.cppba.com

ScheduleApplication.java

其中重點是@EnableScheduling注解,表示啟動定時任務支持

package com.cppba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}

SaySchedule.java

package com.cppba.schedule;

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

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

@Component
public class SaySchedule {

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0/2 * * * * ?")
    public void sayHi() {
        System.out.println("hi!    time is :" + df.format(new Date()));
    }

    @Scheduled(cron = "1/2 * * * * ?")
    public void sayHello() {
        System.out.println("hello! time is :" + df.format(new Date()));
    }
}

核心重點是@Scheduled注解,@Scheduled支持多種類型的計劃任務:cron、fixDelay、fixRate,最流行的還是cron表達式,
在這里推薦一個cron表達式在線生成器:http://cron.qqe2.com/


功能很強大,可以圖形化配置cron表達式,也可以泛解析cron表達式的執(zhí)行時間,特別方便

運行項目

控制臺打印如下:

hi!    time is :2017-08-22 22:40:08
hello! time is :2017-08-22 22:40:09
hi!    time is :2017-08-22 22:40:10
hello! time is :2017-08-22 22:40:11
hi!    time is :2017-08-22 22:40:12
hello! time is :2017-08-22 22:40:13
hi!    time is :2017-08-22 22:40:14
hello! time is :2017-08-22 22:40:15
hi!    time is :2017-08-22 22:40:16
hello! time is :2017-08-22 22:40:17
hi!    time is :2017-08-22 22:40:18
hello! time is :2017-08-22 22:40:19
hi!    time is :2017-08-22 22:40:20
hello! time is :2017-08-22 22:40:21
hi!    time is :2017-08-22 22:40:22
hello! time is :2017-08-22 22:40:23
hi!    time is :2017-08-22 22:40:24

hello和hi交替執(zhí)行,因為我們配置的cron表達式是:sayHi方法從0秒開始,每兩秒執(zhí)行一次;sayHello方法從1秒開始,每兩秒執(zhí)行一次。

到此,我們的定時任務運行成功!

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評論 19 139
  • 博客原文 徒手翻譯spring framework 4.2.3官方文檔的第33章,若有翻譯不當之處請指正。 定時任...
    rabbitGYK閱讀 5,860評論 4 24
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,366評論 25 708
  • 慢生活.淡味道 慢生活--慢節(jié)奏地生活。 “慢生活”一詞,最早看到是在朱德庸的訪談中。喜歡朱德庸的漫畫,更喜歡朱德...
    梅洛的聽雨軒閱讀 199評論 1 0
  • 第三十七章 回家之后余景灝把京東,淘寶之類的網(wǎng)站逛了無數(shù)圈,依然不知道要送平生什么。余景灝看著電腦發(fā)愁,萬能的淘寶...
    星如雨雨雨閱讀 360評論 0 0

友情鏈接更多精彩內(nèi)容