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

前言

前幾節咱們用第三方框架quarz實現了定時任務,實際上spring3.1開始,spring已經內置了定時任務的支持,實現很是簡單,下面咱們一塊兒看看怎麼實現java

ScheduleApplication.java

其中重點是@EnableScheduling註解,表示啓動定時任務支持spring

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表達式的執行時間,特別方便spa

 

運行項目

控制檯打印以下:code

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交替執行,由於咱們配置的cron表達式是:sayHi方法從0秒開始,每兩秒執行一次;sayHello方法從1秒開始,每兩秒執行一次。orm

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

相關文章
相關標籤/搜索