Spring Task定時任務的配置和使用

Spring Task

記錄下Spring自帶的定時任務用法。html

spring中使用定時任務

基於xml配置文件使用定時任務

首先配置spring開啓定時任務java

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">  
  
    <task:annotation-driven /> <!-- 定時器開關-->  
  
    <bean id="myTask" class="com.spring.task.MyTask"></bean>  
  
    <task:scheduled-tasks>  
        <!-- 這裏表示的是每隔五秒執行一次 -->  
        <task:scheduled ref="myTask" method="show" cron="*/5 * * * * ?" />  
        <task:scheduled ref="myTask" method="print" cron="*/10 * * * * ?"/>  
    </task:scheduled-tasks>  
      
    <!-- 自動掃描的包名 -->
    <context:component-scan base-package="com.spring.task" />  
      
</beans>  
複製代碼

定義本身的任務執行邏輯spring

package com.spring.task;  
  
/** 
 * 定義任務 
 */  
public class MyTask {  
      
    public void show() {  
        System.out.println("show method 1");  
    }  
      
    public void print() {  
        System.out.println("print method 1");  
    }  
} 
複製代碼

基於註解使用定時任務

package com.spring.task;  
import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;  
  
/**
 * 基於註解的定時器  
 */
@Component
public class MyTask2 {  

    /**
     * 定時計算。天天凌晨 01:00 執行一次
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void show() {
        System.out.println("show method 2");  
    }  
      
    /**
     * 啓動時執行一次,以後每隔2秒執行一次  
     */
    @Scheduled(fixedRate = 1000*2)   
    public void print() {  
        System.out.println("print method 2");
    }
}
複製代碼

這樣,當項目啓動,定時任務就會按照規則按時執行了。springboot

Spring Boot中使用定時任務

Spring Boot中使用更加方便。bash

  • 引入springboot starter
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
</dependency>
複製代碼
  • 在程序入口啓動類添加@EnableScheduling,開啓定時任務功能
@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
複製代碼
  • 定義定時任務邏輯
@Component
public class MyTask3 {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    private void process() {
        System.out.println("this is scheduler task runing "+(count++));
    }
}
複製代碼

任務執行規則說明

先來看看@Scheduled註解的源碼服務器

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

	String cron() default "";

	String zone() default "";

	long fixedDelay() default -1;

	String fixedDelayString() default "";

	long fixedRate() default -1;

	String fixedRateString() default "";

	long initialDelay() default -1;

	String initialDelayString() default "";
}
複製代碼

能夠看出,註解中能夠傳8種參數:spring-boot

  • cron:指定cron表達式
  • zone:默認使用服務器默認時區。能夠設置爲java.util.TimeZone中的zoneId
  • fixedDelay:從上一個任務完成開始到下一個任務開始的間隔,單位毫秒
  • fixedDelayString:同上,時間值是String類型
  • fixedRate:從上一個任務開始到下一個任務開始的間隔,單位毫秒
  • fixedRateString:同上,時間值是String類型
  • initialDelay:任務首次執行延遲的時間,單位毫秒
  • initialDelayString:同上,時間值是String類型

cron表達式的使用方法

Cron表達式是一個字符串,字符串以5或6個空格隔開,分爲6或7個域,每個域表明一個含義,Cron有以下兩種語法格式:this

  • Seconds Minutes Hours DayofMonth Month DayofWeek Year
  • Seconds Minutes Hours DayofMonth Month DayofWeek

每個域可出現的字符以下:spa

  • Seconds: 可出現", - * /"四個字符,有效範圍爲0-59的整數
  • Minutes: 可出現", - * /"四個字符,有效範圍爲0-59的整數
  • Hours: 可出現", - * /"四個字符,有效範圍爲0-23的整數
  • DayofMonth: 可出現", - * / ? L W C"八個字符,有效範圍爲0-31的整數
  • Month: 可出現", - * /"四個字符,有效範圍爲1-12的整數或JAN-DEC
  • DayofWeek: 可出現", - * / ? L C #"四個字符,有效範圍爲1-7的整數或SUN-SAT兩個範圍。1表示星期天,2表示星期一, 依次類推
  • Year: 可出現", - * /"四個字符,有效範圍爲1970-2099年

每個域都使用數字,但還能夠出現以下特殊字符,它們的含義是:code

  1. *:表示匹配該域的任意值,假如在Minutes域使用*, 即表示每分鐘都會觸發事件。
  2. ?:只能用在DayofMonth和DayofWeek兩個域。它也匹配域的任意值,但實際不會。由於DayofMonth和 DayofWeek會相互影響。例如想在每個月的20日觸發調度,無論20日究竟是星期幾,則只能使用以下寫法: 13 13 15 20 * ?, 其中最後一位只能用?,而不能使用*,若是使用*表示無論星期幾都會觸發,實際上並非這樣。
  3. -:表示範圍,例如在Minutes域使用5-20,表示從5分到20分鐘每分鐘觸發一次。
  4. /:表示起始時間開始觸發,而後每隔固定時間觸發一次,例如在Minutes域使用5/20,則意味着5分鐘觸發一次,而25,45等分別觸發一次。
  5. ,:表示列出枚舉值值。例如:在Minutes域使用5,20,則意味着在5和20分每分鐘觸發一次。
  6. L:表示最後,只能出如今DayofWeek和DayofMonth域,若是在DayofWeek域使用5L,意味着在最後的一個星期四觸發。
  7. W:表示有效工做日(週一到週五),只能出如今DayofMonth域,系統將在離指定日期的最近的有效工做日觸發事件。例如:在 DayofMonth使用5W,若是5日是星期六,則將在最近的工做日:星期五,即4日觸發。若是5日是星期天,則在6日(週一)觸發;若是5日在星期一 到星期五中的一天,則就在5日觸發。另一點,W的最近尋找不會跨過月份。
  8. LW:這兩個字符能夠連用,表示在某個月最後一個工做日,即最後一個星期五。
  9. #:用於肯定每月第幾個星期幾,只能出如今DayofMonth域。例如在4#2,表示某月的第二個星期三。

參考 cron表達式例子

相關文章
相關標籤/搜索