1. 程式人生 > >Springboot之使用Scheduled做定時任務

Springboot之使用Scheduled做定時任務

結束 gif onf argument ike ise red fig import

定時任務有好多開源框架比如Quartz,@Scheduled是Spring的一個定時任務註解,通過註解配置就能夠輕量級的定時任務,簡單方便。

一、@Scheduled註解介紹

這裏先貼上@Scheduled註解。然後下面的這幾個屬性的介紹。

技術分享圖片
 * Copyright 2002-2018 the original author or authors.

package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that marks a method to be scheduled. Exactly one of * the {@link #cron()}, {@link #fixedDelay()}, or {@link #fixedRate()} * attributes must be specified. * * <p>The annotated method must expect no arguments. It will typically have * a {
@code void} return type; if not, the returned value will be ignored * when called through the scheduler. * * <p>Processing of {@code @Scheduled} annotations is performed by * registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be * done manually or, more conveniently, through the {
@code <task:annotation-driven/>} * element or @{@link EnableScheduling} annotation. * * <p>This annotation may be used as a <em>meta-annotation</em> to create custom * <em>composed annotations</em> with attribute overrides. * * @author Mark Fisher * @author Dave Syer * @author Chris Beams * @since 3.0 * @see EnableScheduling * @see ScheduledAnnotationBeanPostProcessor * @see Schedules */ @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { /** * A cron-like expression, extending the usual UN*X definition to include * triggers on the second as well as minute, hour, day of month, month * and day of week. e.g. {@code "0 * * * * MON-FRI"} means once per minute on * weekdays (at the top of the minute - the 0th second). * @return an expression that can be parsed to a cron schedule * @see org.springframework.scheduling.support.CronSequenceGenerator */ String cron() default ""; /** * A time zone for which the cron expression will be resolved. By default, this * attribute is the empty String (i.e. the server‘s local time zone will be used). * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)}, * or an empty String to indicate the server‘s default time zone * @since 4.0 * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone) * @see java.util.TimeZone */ String zone() default ""; /** * Execute the annotated method with a fixed period in milliseconds between the * end of the last invocation and the start of the next. * @return the delay in milliseconds */ long fixedDelay() default -1; /** * Execute the annotated method with a fixed period in milliseconds between the * end of the last invocation and the start of the next. * @return the delay in milliseconds as a String value, e.g. a placeholder * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @since 3.2.2 */ String fixedDelayString() default ""; /** * Execute the annotated method with a fixed period in milliseconds between * invocations. * @return the period in milliseconds */ long fixedRate() default -1; /** * Execute the annotated method with a fixed period in milliseconds between * invocations. * @return the period in milliseconds as a String value, e.g. a placeholder * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @since 3.2.2 */ String fixedRateString() default ""; /** * Number of milliseconds to delay before the first execution of a * {@link #fixedRate()} or {@link #fixedDelay()} task. * @return the initial delay in milliseconds * @since 3.2 */ long initialDelay() default -1; /** * Number of milliseconds to delay before the first execution of a * {@link #fixedRate()} or {@link #fixedDelay()} task. * @return the initial delay in milliseconds as a String value, e.g. a placeholder * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @since 3.2.2 */ String initialDelayString() default ""; }
View Code

cron屬性
這是一個時間表達式,可以通過簡單的配置就能完成各種時間的配置,我們通過CRON表達式幾乎可以完成任意的時間搭配,它包含了六或七個域:
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年
"0 0 12 * * ?" 每天中午十二點觸發
"0 15 10 ? * *" 每天早上10:15觸發
"0 15 10 * * ?" 每天早上10:15觸發
"0 15 10 * * ? *" 每天早上10:15觸發
"0 15 10 * * ? 2005" 2005年的每天早上10:15觸發
"0 * 14 * * ?" 每天從下午2點開始到2點59分每分鐘一次觸發
"0 0/5 14 * * ?" 每天從下午2點開始到2:55分結束每5分鐘一次觸發
"0 0/5 14,18 * * ?" 每天的下午2點至2:55和6點至6點55分兩個時間段內每5分鐘一次觸發
"0 0-5 14 * * ?" 每天14:00至14:05每分鐘一次觸發
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44觸發
"0 15 10 ? * MON-FRI" 每個周一、周二、周三、周四、周五的10:15觸發

fixedRate屬性
上一個調用開始後再次調用的延時(不用等待上一次調用完成),這樣就會存在重復執行的問題,所以不是建議使用,但數據量如果不大時在配置的間隔時間內可以執行完也是可以使用的。

fixedDelay屬性
該屬性的功效與上面的fixedRate則是相反的,配置了該屬性後會等到方法執行完成後延遲配置的時間再次執行該方法。

initialDelay屬性
該屬性跟上面的fixedDelay、fixedRate有著密切的關系,為什麽這麽說呢?該屬性的作用是第一次執行延遲時間,只是做延遲的設定,並不會控制其他邏輯,所以要配合fixedDelay或者fixedRate來使用。

二、@Scheduled註解實例

package com.example.demo;

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

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

@Component
public class SchedulerTask {
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 10000)
    public void timerRate() {
        System.out.println(dateFormat.format(new Date()));
    }
    
    //第一次延遲1秒執行,當執行完後2秒再執行
    @Scheduled(initialDelay = 1000, fixedDelay = 2000)
    public void timerInit() {
        System.out.println("init : "+dateFormat.format(new Date()));
    }

    //每天21點41分50秒執行
    @Scheduled(cron = "50 41 21 * * ?")
    public void timerCron() {
        System.out.println("current time : "+ dateFormat.format(new Date()));
    }
}

代碼都使用了上了的@Scheduled屬性。下圖是執行打印的日誌信息,timerInit方法是每隔2秒執行,timerCron設置在21點41分50秒執行,timerRate是每隔10秒執行。

技術分享圖片

三、添加@EnableScheduling註解

上面的定時任務並不能執行,還需要一步,需要設置開啟定時任務,這個也很簡單,只需在main方法上加上@EnableScheduling註解即可。

package com.example.demo;

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

@EnableScheduling
@SpringBootApplication
public class TestApplication {

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

Springboot之使用Scheduled做定時任務