一、前言
在Java中有三種實(shí)現(xiàn)定時(shí)任務(wù)的方式:1.java自帶的API java.util.Timer類 java.util.TimerTask類。2.Quartz框架 開源 功能強(qiáng)大 使用起來稍顯復(fù)雜. 3.Spring 3.0以后自帶了task 調(diào)度工具,比Quartz更加的簡單方便.
二、使用
Spring從3.0后自帶了task調(diào)度工具,不需要引入其他的第三方依賴。在啟動(dòng)類上添加@EnableScheduling注解
ScheduleTask.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduleTask {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Scheduled(cron = "0 0 2 * * ?")
public void queryNumber(){
try {
System.out.println("定時(shí)任務(wù)執(zhí)行了");
} catch (Exception e) {
logger.error("定時(shí)任務(wù)發(fā)生了錯(cuò)誤,錯(cuò)誤信息為:"+e.getMessage());
}
}
}
在需要定時(shí)執(zhí)行的方法上添加@Scheduled注解并指定cron的值,上面的這個(gè)例子讓打印語句每天凌晨兩點(diǎn)執(zhí)行一次。
三、@Scheduled注解詳解
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* 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 Juergen Hoeller
* @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 special cron expression value that indicates a disabled trigger: {@value}.
* <p>This is primarily meant for use with <code>${...}</code> placeholders,
* allowing for external disabling of corresponding scheduled methods.
* @since 5.1
* @see ScheduledTaskRegistrar#CRON_DISABLED
*/
String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;
/**
* A cron-like expression, extending the usual UN*X definition to include triggers
* on the second, minute, hour, day of month, month, and day of week.
* <p>For example, {@code "0 * * * * MON-FRI"} means once per minute on weekdays
* (at the top of the minute - the 0th second).
* <p>The fields read from left to right are interpreted as follows.
* <ul>
* <li>second</li>
* <li>minute</li>
* <li>hour</li>
* <li>day of month</li>
* <li>month</li>
* <li>day of week</li>
* </ul>
* <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron
* trigger, primarily meant for externally specified values resolved by a
* <code>${...}</code> placeholder.
* @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 "";
}
這個(gè)注解標(biāo)記了一個(gè)將要被定時(shí)執(zhí)行的方法,cron、fixedDelay與fixedRate三個(gè)屬性必選其一。
被注解的方法不能傳入?yún)?shù),通常有一個(gè)void的返回值,如果不是,返回值將會(huì)被忽略。
cron是一個(gè)類似cron的表達(dá)式,可以指定秒、分、時(shí)、一個(gè)月的第幾天、月、一周的星期幾。例如,"0 * * * * MON-FRI"表示工作日的每一分鐘都執(zhí)行。
zone指定了cron表達(dá)式的時(shí)區(qū)。如果未指定,則是服務(wù)器的默認(rèn)時(shí)區(qū)。
fixedDelay:執(zhí)行注解方法的固定的毫秒數(shù)間隔,這個(gè)間隔是指上一次調(diào)用的結(jié)束和下一次調(diào)用的開始的時(shí)間。
fixedRate:執(zhí)行注解方法的固定的毫秒數(shù)間隔,這個(gè)間隔是指每次調(diào)用之間的時(shí)間。與上面的區(qū)別是:fixedDelay是前一個(gè)方法執(zhí)行完畢后的固定時(shí)間再執(zhí)行下一個(gè)方法,fixedRate是上一個(gè)方法開始執(zhí)行固定時(shí)間后執(zhí)行下一個(gè)方法。
四、cron表達(dá)式
1、分類
cron表達(dá)式可以分為兩種:
1、6位長度的 秒 分 時(shí) 日 月 星期
2、7位長度的 秒 分 時(shí) 日 月 星期 年
一般都是用6位長度的。
2、每個(gè)位置可以出現(xiàn)的字符
秒: 可出現(xiàn) , - * / 四個(gè)字符,有效范圍為0-59的整數(shù)
分: 可出現(xiàn),- * / 四個(gè)字符,有效范圍為0-59的整數(shù)
時(shí): 可出現(xiàn),- * / 四個(gè)字符,有效范圍為0-23的整數(shù)
日: 可出現(xiàn),- * / ? L W C八個(gè)字符,有效范圍為0-31的整數(shù)
月: 可出現(xiàn),- * / 四個(gè)字符,有效范圍為1-12的整數(shù)或JAN-DEC
星期: 可出現(xiàn),- * / ? L C #八個(gè)字符,有效范圍為1-7的整數(shù)或SUN-SAT兩個(gè)范圍。1表示星期天
年: 可出現(xiàn),- * / 四個(gè)字符,有效范圍為1970-2099年
3、字符的含義
(1)*:表示匹配該域的任意值,假如在Minutes域使用*,即表示每分鐘都會(huì)觸發(fā)事件。
(2)?:只能用在DayofMonth和DayofWeek兩個(gè)域。它也匹配域的任意值,但實(shí)際不會(huì)。因?yàn)镈ayofMonth和DayofWeek會(huì)相互影響。
例如想在每月的20日觸發(fā)調(diào)度,不管20日到底是星期幾,則只能使用如下寫法: 13 13 15 20 * ?,其中最后一位只能用?,而不能使用*,如果使用*表示不管星期幾都會(huì)觸發(fā),實(shí)際上并不是這樣。
(3)-:表示范圍,例如在Minutes域使用5-20,表示從5分到20分鐘每分鐘觸發(fā)一次
(4)/:表示起始時(shí)間開始觸發(fā),然后每隔固定時(shí)間觸發(fā)一次,例如在Minutes域使用5/20,則意味著5分鐘觸發(fā)一次,而25,45等分別觸發(fā)一次.
(5),:表示列出枚舉值值。例如:在Minutes域使用5,20,則意味著在5和20分每分鐘觸發(fā)一次。
(6)L:表示最后,只能出現(xiàn)在DayofWeek和DayofMonth域,如果在DayofWeek域使用5L,意味著在最后的一個(gè)星期四觸發(fā)。
(7)W:表示有效工作日(周一到周五),只能出現(xiàn)在DayofMonth域,系統(tǒng)將在離指定日期的最近的有效工作日觸發(fā)事件。
例如:在DayofMonth使用5W,如果5日是星期六,則將在最近的工作日:星期五,即4日觸發(fā)。如果5日是星期天,則在6日觸發(fā);
如果5日在星期一到星期五中的一天,則就在5日觸發(fā)。另外一點(diǎn),W的最近尋找不會(huì)跨過月份
(8)LW:這兩個(gè)字符可以連用,表示在某個(gè)月最后一個(gè)工作日,即最后一個(gè)星期五。
(9)#:用于確定每個(gè)月第幾個(gè)星期幾,只能出現(xiàn)在DayofMonth域。例如在4#2,表示某月的第二個(gè)星期三。
4、cron表達(dá)式舉例
0 0 10,14,16 * * ? 每天上午10點(diǎn),下午2點(diǎn),4點(diǎn)
0 0/30 9-17 * * ? 朝九晚五工作時(shí)間內(nèi)每半小時(shí)
0 0 12 ? * WED 表示每個(gè)星期三中午12點(diǎn)
"0 0 12 * * ?" 每天中午12點(diǎn)觸發(fā)
"0 15 10 ? * *" 每天上午10:15觸發(fā)
"0 15 10 * * ?" 每天上午10:15觸發(fā)
"0 15 10 * * ? *" 每天上午10:15觸發(fā)
"0 15 10 * * ? 2005" 2005年的每天上午10:15觸發(fā)
"0 * 14 * * ?" 在每天下午2點(diǎn)到下午2:59期間的每1分鐘觸發(fā)
"0 0/5 14 * * ?" 在每天下午2點(diǎn)到下午2:55期間的每5分鐘觸發(fā)
"0 0/5 14,18 * * ?" 在每天下午2點(diǎn)到2:55期間和下午6點(diǎn)到6:55期間的每5分鐘觸發(fā)
"0 0-5 14 * * ?" 在每天下午2點(diǎn)到下午2:05期間的每1分鐘觸發(fā)
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44觸發(fā)
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15觸發(fā)
"0 15 10 15 * ?" 每月15日上午10:15觸發(fā)
"0 15 10 L * ?" 每月最后一日的上午10:15觸發(fā)
"0 15 10 ? * 6L" 每月的最后一個(gè)星期五上午10:15觸發(fā)
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一個(gè)星期五上午10:15觸發(fā)
"0 15 10 ? * 6#3" 每月的第三個(gè)星期五上午10:15觸發(fā)
五、多線程定時(shí)任務(wù)
有時(shí)候需要執(zhí)行的定時(shí)任務(wù)會(huì)很多,如果是串行執(zhí)行會(huì)帶來一些問題,比如一個(gè)很耗時(shí)的任務(wù)阻塞住了,一些需要短周期循環(huán)執(zhí)行的任務(wù)也會(huì)卡住,所以可以配置一個(gè)線程池來并行執(zhí)行定時(shí)任務(wù)。
有兩種配置方式,一種是寫一個(gè)配置類創(chuàng)建一個(gè)線程池,另一種是在yml文件中進(jìn)行配置創(chuàng)建線程池。
@EnableAsync //開啟對(duì)異步任務(wù)的支持
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);//線程池維護(hù)線程的最少數(shù)量
taskExecutor.setMaxPoolSize(10);//線程池維護(hù)線程的最大數(shù)量
taskExecutor.setQueueCapacity(25);//緩沖隊(duì)列的數(shù)量
taskExecutor.initialize();//初始化
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@Async //放在類上,表明該類中所有方法都是異步執(zhí)行
public class AsyncTaskService {
@Scheduled("0 15 10 * * ?")
public void executeAysncTask1(Integer i){
System.out.println("executeAysncTask1: " + i);
}
@Scheduled("0 15 10 * * ?")
public void executeAysncTask2(Integer i){
System.out.println("executeAysncTask2: " + i);
}
}
配置文件的方式:
spring:
task:
# spring定時(shí)任務(wù)執(zhí)行器配置,對(duì)于spring的異步任務(wù),會(huì)使用該執(zhí)行器
execution:
thread-name-prefix: mytask- # 線程池的線程名前綴
pool:
core-size: 8 # 核心線程數(shù),線程池創(chuàng)建的時(shí)候初始化的線程數(shù)
max-size: 20 # 最大線程數(shù),緩沖隊(duì)列滿了后才會(huì)申請(qǐng)超過核心線程數(shù)的線程
keep-alive: 60s # 非核心線程的允許最大空閑時(shí)間
queue-capacity: 200 # 緩沖隊(duì)列大小,用來緩沖執(zhí)行任務(wù)的隊(duì)列的大小
allow-core-thread-timeout: true # 是否允許核心線程超時(shí),即開啟線程池的動(dòng)態(tài)增長和縮小,默認(rèn)為true
shutdown: # 實(shí)現(xiàn)異步任務(wù)的優(yōu)雅關(guān)閉
await-termination: true # 應(yīng)用關(guān)閉時(shí),是否等待定時(shí)任務(wù)執(zhí)行完成
await-termination-period: 60 # 等待任務(wù)完成的最大時(shí)長,單位為秒