您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Java Spring怎么實(shí)現(xiàn)定時(shí)任務(wù)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Java Spring怎么實(shí)現(xiàn)定時(shí)任務(wù)”吧!
Jdk自帶的庫(kù)中,有兩種方式可以實(shí)現(xiàn)定時(shí)任務(wù),一種是Timer
,另一種是ScheduledThreadPoolExecutor
。
創(chuàng)建一個(gè)Timer
就創(chuàng)建了一個(gè)線程,可以用來調(diào)度TimerTask
任務(wù)
Timer
有四個(gè)構(gòu)造方法,可以指定Timer
線程的名字以及是否設(shè)置為為守護(hù)線程。默認(rèn)名字Timer-編號(hào)
,默認(rèn)不是守護(hù)線程。
主要有三個(gè)比較重要的方法:
cancel()
:終止任務(wù)調(diào)度,取消當(dāng)前調(diào)度的所有任務(wù),正在運(yùn)行的任務(wù)不受影響
purge()
:從任務(wù)隊(duì)列中移除所有已經(jīng)取消的任務(wù)
schedule
:開始調(diào)度任務(wù),提供了幾個(gè)重載方法:
schedule(TimerTask task, long delay)
延時(shí)執(zhí)行,表示delay
毫秒后執(zhí)行一次task
任務(wù)
schedule(TimerTask task, Date time)`指定時(shí)間執(zhí)行,到`time`時(shí)間的時(shí)候執(zhí)行一次`task
schedule(TimerTask task, long delay, long period)`延時(shí)周期執(zhí)行,經(jīng)過`delay`毫秒后每`period`毫秒執(zhí)行一次`task
schedule(TimerTask task, Date firstTime, long period)`指定時(shí)間后周期執(zhí)行,到達(dá)指定時(shí)間`firstTime`后每`period`毫秒執(zhí)行一次`task
public class TimerTest { public static void main(String[] args) { Timer timer = new Timer("aa"); Task task = new Task(); timer.schedule(task,new Date(),1000); } } class Task extends TimerTask{ @Override public void run() { System.out.println(new Date()); } }
輸出:
Thu Jul 07 14:50:02 CST 2022
Thu Jul 07 14:50:03 CST 2022
Thu Jul 07 14:50:04 CST 2022
Thu Jul 07 14:50:05 CST 2022
…………
Timer是單線程的,并且不會(huì)拋出異常,一旦定時(shí)任務(wù)拋出異常,將會(huì)導(dǎo)致整個(gè)線程停止,即定時(shí)任務(wù)停止。
因?yàn)?code>Timer的缺陷,所以不建議使用Timer
,建議使用ScheduledThreadPoolExecutor
。
ScheduledThreadPoolExecutor
是Timer
的替代者,于JDK1.5引入,繼承了ThreadPoolExecutor
,是基于線程池設(shè)計(jì)的定時(shí)任務(wù)類。
主要的調(diào)度方法:
schedule
只執(zhí)行一次調(diào)度,(任務(wù),延遲時(shí)間,延遲時(shí)間單位)
scheduleAtFixedRate
按固定的頻率調(diào)度,如果執(zhí)行時(shí)間過長(zhǎng),下次調(diào)度會(huì)延遲,(任務(wù),第一次執(zhí)行的延遲時(shí)間,周期,時(shí)間單位)
scheduleWithFixedDelay
延遲調(diào)度,一次任務(wù)執(zhí)行完后加上延遲時(shí)間執(zhí)行下一次任務(wù),(任務(wù),第一次執(zhí)行的延遲時(shí)間,間隔時(shí)間,時(shí)間單位)
public class TimerTest { public static void main(String[] args) throws Exception{ ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); scheduledExecutorService.scheduleAtFixedRate( () -> System.out.println(new Date()), 1,3, TimeUnit.SECONDS); } }
Spring定時(shí)任務(wù)主要靠@Scheduled
注解實(shí)現(xiàn),corn,fixedDelay,fixedDelayString,fixedRate,fixedRateString
五個(gè)參數(shù)必須指定其一,傳兩個(gè)或三個(gè)都會(huì)拋出異常
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED; // cron表達(dá)式 String cron() default ""; // 時(shí)區(qū) String zone() default ""; // 從上一次調(diào)用結(jié)束到下一次調(diào)用之間的固定時(shí)間 long fixedDelay() default -1; // 和fixedDelay意思相同,只是使用字符傳格式,支持占位符。例如:fixedDelayString = "${time.fixedDelay}" String fixedDelayString() default ""; // 兩次調(diào)用之間固定的毫秒數(shù)(不需要等待上次任務(wù)完成) long fixedRate() default -1; // 同上,支持占位符 String fixedRateString() default ""; // 第一次執(zhí)行任務(wù)前延遲的毫秒數(shù) long initialDelay() default -1; // 同上,支持占位符 String initialDelayString() default ""; }
@Component @EnableScheduling public class ScheduledTask { @Scheduled(fixedDelay = 1000) public void task(){ System.out.println("aaa"); } }
項(xiàng)目啟動(dòng)ScheduledAnnotationBeanPostProcessor
的postProcessAfterInitialization()
方法掃描帶有@Scheduled
注解的方法:
@Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler || bean instanceof ScheduledExecutorService) { // Ignore AOP infrastructure such as scoped proxies. return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass) && AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) { Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> { Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations( method, Scheduled.class, Schedules.class); return (!scheduledMethods.isEmpty() ? scheduledMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); if (logger.isTraceEnabled()) { logger.trace("No @Scheduled annotations found on bean class: " + targetClass); } } else { // Non-empty set of methods annotatedMethods.forEach((method, scheduledMethods) -> // 調(diào)用processScheduled方法將定時(shí)任務(wù)的方法存放到任務(wù)隊(duì)列中 scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean))); if (logger.isTraceEnabled()) { logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName + "': " + annotatedMethods); } } } return bean; }
protected void processScheduled(Scheduled scheduled, Method method, Object bean) { try { // 創(chuàng)建任務(wù)線程 Runnable runnable = createRunnable(bean, method); // 解析到定時(shí)任務(wù)方式的標(biāo)記,解析到正確的參數(shù)后會(huì)設(shè)置為TRUE,如果在解析到了其他的參數(shù)就會(huì)拋出異常 boolean processedSchedule = false; String errorMessage = "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required"; Set<ScheduledTask> tasks = new LinkedHashSet<>(4); // Determine initial delay 解析第一次的延遲(解析initialDelay參數(shù)) long initialDelay = scheduled.initialDelay(); String initialDelayString = scheduled.initialDelayString(); if (StringUtils.hasText(initialDelayString)) { // initialDelay不能小于0 Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both"); if (this.embeddedValueResolver != null) { initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString); } if (StringUtils.hasLength(initialDelayString)) { try { initialDelay = parseDelayAsLong(initialDelayString); } catch (RuntimeException ex) { throw new IllegalArgumentException( "Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into long"); } } } // Check cron expression 解析cron表達(dá)式 String cron = scheduled.cron(); if (StringUtils.hasText(cron)) { // 解析時(shí)區(qū) String zone = scheduled.zone(); if (this.embeddedValueResolver != null) { cron = this.embeddedValueResolver.resolveStringValue(cron); zone = this.embeddedValueResolver.resolveStringValue(zone); } if (StringUtils.hasLength(cron)) { Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers"); processedSchedule = true; if (!Scheduled.CRON_DISABLED.equals(cron)) { TimeZone timeZone; if (StringUtils.hasText(zone)) { timeZone = StringUtils.parseTimeZoneString(zone); } else { timeZone = TimeZone.getDefault(); } tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone)))); } } } // 第一次延遲參數(shù)小于0,默認(rèn)為0 // At this point we don't need to differentiate between initial delay set or not anymore if (initialDelay < 0) { initialDelay = 0; } // Check fixed delay 解析fixedDelay參數(shù) long fixedDelay = scheduled.fixedDelay(); if (fixedDelay >= 0) { Assert.isTrue(!processedSchedule, errorMessage); processedSchedule = true; tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay))); } String fixedDelayString = scheduled.fixedDelayString(); if (StringUtils.hasText(fixedDelayString)) { if (this.embeddedValueResolver != null) { fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString); } if (StringUtils.hasLength(fixedDelayString)) { Assert.isTrue(!processedSchedule, errorMessage); processedSchedule = true; try { fixedDelay = parseDelayAsLong(fixedDelayString); } catch (RuntimeException ex) { throw new IllegalArgumentException( "Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into long"); } tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay))); } } // Check fixed rate 解析fixedRate參數(shù) long fixedRate = scheduled.fixedRate(); if (fixedRate >= 0) { Assert.isTrue(!processedSchedule, errorMessage); processedSchedule = true; tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay))); } String fixedRateString = scheduled.fixedRateString(); if (StringUtils.hasText(fixedRateString)) { if (this.embeddedValueResolver != null) { fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString); } if (StringUtils.hasLength(fixedRateString)) { Assert.isTrue(!processedSchedule, errorMessage); processedSchedule = true; try { fixedRate = parseDelayAsLong(fixedRateString); } catch (RuntimeException ex) { throw new IllegalArgumentException( "Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into long"); } tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay))); } } // Check whether we had any attribute set // 如果五個(gè)參數(shù)一個(gè)也沒解析到,拋出異常 Assert.isTrue(processedSchedule, errorMessage); // Finally register the scheduled tasks // 并發(fā)控制將任務(wù)隊(duì)列存入注冊(cè)任務(wù)列表 synchronized (this.scheduledTasks) { Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4)); regTasks.addAll(tasks); } } catch (IllegalArgumentException ex) { throw new IllegalStateException( "Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage()); } }
將任務(wù)解析并添加到任務(wù)隊(duì)列后,交由ScheduledTaskRegistrar
類的scheduleTasks
方法添加(注冊(cè))定時(shí)任務(wù)到環(huán)境中
protected void scheduleTasks() { if (this.taskScheduler == null) { //獲取ScheduledExecutorService對(duì)象,實(shí)際上都是使用ScheduledThreadPoolExecutor執(zhí)行定時(shí)任務(wù)調(diào)度 this.localExecutor = Executors.newSingleThreadScheduledExecutor(); this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor); } if (this.triggerTasks != null) { for (TriggerTask task : this.triggerTasks) { addScheduledTask(scheduleTriggerTask(task)); } } if (this.cronTasks != null) { for (CronTask task : this.cronTasks) { addScheduledTask(scheduleCronTask(task)); } } if (this.fixedRateTasks != null) { for (IntervalTask task : this.fixedRateTasks) { addScheduledTask(scheduleFixedRateTask(task)); } } if (this.fixedDelayTasks != null) { for (IntervalTask task : this.fixedDelayTasks) { addScheduledTask(scheduleFixedDelayTask(task)); } } } private void addScheduledTask(@Nullable ScheduledTask task) { if (task != null) { this.scheduledTasks.add(task); } }
到此,相信大家對(duì)“Java Spring怎么實(shí)現(xiàn)定時(shí)任務(wù)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。