SpringBoot -- 計劃任務

   從Spring 3.1 開始,計劃任務在Spring中的實現變得異常的簡單。首先經過在配置類註解@EnableScheduling 來開啓對計劃任務的支持,而後再執行集合任務的方法上註解@Scheduled,聲明這是一個計劃任務。java

  Spring經過@Scheduled支持多種類的計劃任務,包含cron、fixDelay、fixRate等。spring

1、計劃任務執行類spa

package com.cenobitor.scheduler.taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)//1
    public void reportCurrentTime(){
        System.out.println("每隔五秒執行一次 "+DATE_FORMAT.format(new Date()));
    }

    @Scheduled(cron = "0 02 22 ? * *")//
    public void fixTimeExecution(){
        System.out.println("在指定時間 "+DATE_FORMAT.format(new Date())+"執行");
    }
}

一、通@Sceduled聲明該方法是計劃任務,使用fixedRate屬性每隔固定時間執行。code

二、使用cron屬性可按照指定時間執行,本例指天天22點02分執行。orm

2、運行blog

package com.cenobitor.scheduler;

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

@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {

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

  使用@EnableScheduling註解開啓對計劃任務的支持。開發

運行結果:it

每隔五秒執行一次 22:01:54
每隔五秒執行一次 22:01:59
在指定時間 22:02:00執行
每隔五秒執行一次 22:02:04io

  注:摘抄自《JavaEE開發的顛覆者SpringBoot 實戰》。form

相關文章
相關標籤/搜索