@Scheduled
註解參數:
- cron:cron表達式,指定任務在特定時間執行;
- fixedDelay:表示上一次任務執行完成後多久再次執行,參數類型爲long,單位ms;
- fixedDelayString:與fixedDelay含義一樣,只是參數類型變爲String;
- fixedRate:表示按一定的頻率執行任務,參數類型爲long,單位ms;
- fixedRateString: 與fixedRate的含義一樣,只是將參數類型變爲String;
- initialDelay:表示延遲多久再第一次執行任務,參數類型爲long,單位ms;
- initialDelayString:與initialDelay的含義一樣,只是將參數類型變爲String;
- zone:時區,默認爲當前時區。
cron表達式語法
[秒] [分] [小時] [日] [月] [周] [年]
序號 | 說明 | 必填 | 允許填寫的值 | 允許的通配符 |
---|---|---|---|---|
1 | 秒 | 是 | 0-59 | , - * / |
2 | 分 | 是 | 0-59 | , - * / |
3 | 時 | 是 | 0-23 | , - * / |
4 | 日 | 是 | 1-31 | , - * ? / L W |
5 | 月 | 是 | 1-12 / JAN-DEC | , - * / |
6 | 周 | 是 | 1-7 or SUN-SAT | , - * ? / L # |
7 | 年 | 否 | 1970-2099 | , - * / |
通配符說明:
*
表示所有值。 例如:在分的字段上設置 *,表示每一分鐘都會觸發。?
表示不指定值。使用的場景爲不需要關心當前設置這個字段的值。例如:要在每月的10號觸發一個操作,但不關心是周幾,所以需要周位置的那個字段設置爲”?” 具體設置爲 0 0 0 10 * ?-
表示區間。例如 在小時上設置 “10-12”,表示 10,11,12點都會觸發。,
表示指定多個值,例如在周字段上設置 “MON,WED,FRI” 表示週一,週三和週五觸發/
用於遞增觸發。如在秒上面設置”5/15” 表示從5秒開始,每增15秒觸發(5,20,35,50)。 在日字段上設置’1/3’所示每月1號開始,每隔三天觸發一次。L
表示最後的意思。在日字段設置上,表示當月的最後一天(依據當前月份,如果是二月還會依據是否是潤年[leap]), 在周字段上表示星期六,相當於”7”或”SAT”。如果在”L”前加上數字,則表示該數據的最後一個。例如在周字段上設置”6L”這樣的格式,則表示“本月最後一個星期五”W
表示離指定日期的最近那個工作日(週一至週五). 例如在日字段上置”15W”,表示離每月15號最近的那個工作日觸發。如果15號正好是週六,則找最近的週五(14號)觸發, 如果15號是周未,則找最近的下週一(16號)觸發.如果15號正好在工作日(週一至週五),則就在該天觸發。如果指定格式爲 “1W”,它則表示每月1號往後最近的工作日觸發。如果1號正是週六,則將在3號下週一觸發。(注,”W”前只能設置具體的數字,不允許區間”-“)。#
序號(表示每月的第幾個周幾),例如在周字段上設置”6#3”表示在每月的第三個週六.注意如果指定”#5”,正好第五週沒有周六,則不會觸發該配置(用在母親節和父親節再合適不過了) ;小提示:’L’和 ‘W’可以一組合使用。如果在日字段上設置”LW”,則表示在本月的最後一個工作日觸發;周字段的設置,若使用英文字母是不區分大小寫的,即MON與mon相同。
示例
每隔5秒執行一次:*/5 * * * * ?
每隔1分鐘執行一次:0 */1 * * * ?
每天23點執行一次:0 0 23 * * ?
每天凌晨1點執行一次:0 0 1 * * ?
每月1號凌晨1點執行一次:0 0 1 1 * ?
每月最後一天23點執行一次:0 0 23 L * ?
每週星期六凌晨1點實行一次:0 0 1 ? * L
在26分、29分、33分執行一次:0 26,29,33 * * * ?
每天的0點、13點、18點、21點都執行一次:0 0 0,13,18,21 * * ?
2. zone
時區,接收一個java.util.TimeZone#ID
。cron表達式
會基於該時區解析。默認是一個空字符串,即取服務器所在地的時區。比如我們一般使用的時區Asia/Shanghai
。該字段我們一般留空。
3. fixedDelay
上一次執行完畢時間點之後多長時間再執行。如:
@Scheduled(fixedDelay = 5000) //上一次執行完畢時間點之後5秒再執行
4. fixedDelayString
與 3. fixedDelay
意思相同,只是使用字符串的形式。唯一不同的是支持佔位符。如:
@Scheduled(fixedDelayString = "5000") //上一次執行完畢時間點之後5秒再執行
佔位符的使用(配置文件中有配置:time.fixedDelay=5000):
@Scheduled(fixedDelayString = "${time.fixedDelay}")
void testFixedDelayString() {
System.out.println("Execute at " + System.currentTimeMillis());
}
運行結果:
佔位符的使用
5. fixedRate
上一次開始執行時間點之後多長時間再執行。如:
@Scheduled(fixedRate = 5000) //上一次開始執行時間點之後5秒再執行
6. fixedRateString
與 5. fixedRate
意思相同,只是使用字符串的形式。唯一不同的是支持佔位符。
7. initialDelay
第一次延遲多長時間後再執行。如:
@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
8. initialDelayString
與 7. initialDelay
意思相同,只是使用字符串的形式。唯一不同的是支持佔位符。
That's all ! Thanks for reading.
另外如果要想@Scheduled註解生效需要添加配置
package com.example.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 在用springboot框架做定時任務的時候,大部分情況都是直接通過@Scheduled註解來指定定時任務的。
* 但是當你有多個定時任務時,@Scheduled並不一定會按時執行。
* 因爲使用@Scheduled的定時任務雖然是異步執行的,但是,默認不同的定時任務之間並不是並行的。
*
* 當未手動指定taskScheduler時,會通過Executors.newSingleThreadScheduledExecutor()創建默認的單線程線程池,
* 且該線程池的拒絕策略爲AbortPolicy,這種策略在線程池無可用線程時丟棄任務,
* 並拋出異常RejectedExecutionException。
*
*/
@Slf4j
@Configuration
@EnableScheduling
@EnableAsync
public class ScheduledConfig implements
SchedulingConfigurer
// , AsyncConfigurer
{
/**
* ThreadPoolTaskExecutor是一個專門用於執行任務的類。
* ThreadPoolTaskScheduler是一個專門用於調度任務的類。
* 一個ThreadPoolTaskExecutor通過它的corePoolSize , maxPoolSize , keepAliveSeconds和queueCapacity屬性在線程池中提供細粒度的配置。
* 諸如ThreadPoolTaskScheduler這樣的調度器不提供這樣的配置。
*/
/** 最大線程數 */
private static final int maxPoolSize = 10;
/** 線程池名前綴 */
private static final String threadNamePrefix = "yu-scheduled-";
@Bean("asyncExecutorScheduled") // bean的名稱,默認爲首字母小寫的方法名,如果不聲明則會使用方法名
public ThreadPoolTaskScheduler asyncExecutorScheduled(){
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(maxPoolSize);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setAwaitTerminationSeconds(60);
executor.setWaitForTasksToCompleteOnShutdown(true);
// 初始化
executor.initialize();
return executor;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setTaskScheduler(this.asyncExecutorScheduled());
}
// /**
// * 處理異步方法調用時要使用的實例
// * @return
// */
// @Override
// public Executor getAsyncExecutor() {
// return this.asyncExecutorScheduled();
// }
//
// /**
// * 在使用void返回類型的異步方法執行期間拋出異常時要使用的實例。
// * @return
// */
// @Override
// public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// return new SimpleAsyncUncaughtExceptionHandler();
// }
}
或者:
package com.example.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.concurrent.ScheduledThreadPoolExecutor;
/**
* scheduled 配置文件的第二種使用 不建議使用
*/
@Slf4j
@Configuration
@EnableScheduling
public class ScheduledConfig2 {
@Bean
public ScheduledThreadPoolExecutor scheduledExecutorService() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
return executor;
}
}
實例:
package com.example.demo.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @Scehduled 定時任務測試
*/
@Slf4j
@Service
public class ScheduledService {
/**5
*測試
*/
@Scheduled(cron = "*/5 * * * * *")
public void testScheduled1(){
log.info("定時1:{}",new Date());
}
@Scheduled(cron = "*/5 * * * * *")
public void testScheduled2(){
log.info("定時2:{}",new Date());
}
}
結果:
2020-05-25 16:36:00.001 INFO 9116 --- [ yu-scheduled-1] c.example.demo.service.ScheduledService : 定時2:Mon May 25 16:36:00 CST 2020
2020-05-25 16:36:00.005 INFO 9116 --- [ yu-scheduled-2] c.example.demo.service.ScheduledService : 定時1:Mon May 25 16:36:00 CST 2020
2020-05-25 16:36:05.004 INFO 9116 --- [ yu-scheduled-1] c.example.demo.service.ScheduledService : 定時2:Mon May 25 16:36:05 CST 2020
2020-05-25 16:36:05.004 INFO 9116 --- [ yu-scheduled-2] c.example.demo.service.ScheduledService : 定時1:Mon May 25 16:36:05 CST 2020
參考自:https://www.jianshu.com/p/1defb0f22ed1