Spring Boot中實(shí)現(xiàn)定時(shí)任務(wù)應(yīng)用實(shí)踐
前言
在Spring Boot中實(shí)現(xiàn)定時(shí)任務(wù)功能,可以通過(guò)Spring自帶的定時(shí)任務(wù)調(diào)度,也可以通過(guò)集成經(jīng)典開源組件Quartz實(shí)現(xiàn)任務(wù)調(diào)度。
本文將詳細(xì)介紹關(guān)于Spring Boot實(shí)現(xiàn)定時(shí)任務(wù)應(yīng)用的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。
一、Spring定時(shí)器
1、cron表達(dá)式方式
使用自帶的定時(shí)任務(wù),非常簡(jiǎn)單,只需要像下面這樣,加上注解就好,不需要像普通定時(shí)任務(wù)框架那樣繼承任何定時(shí)處理接口 ,簡(jiǎn)單示例代碼如下:
package com.power.demo.scheduledtask.simple; import com.power.demo.util.DateTimeUtil; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component @EnableScheduling public class SpringTaskA { /** * CRON表達(dá)式參考:http://cron.qqe2.com/ **/ @Scheduled(cron = "*/5 * * * * ?", zone = "GMT+8:00") private void timerCron() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(timerCron)%s 每隔5秒執(zhí)行一次,記錄日志", DateTimeUtil.fmtDate(new Date()))); } } SpringTaskA
上述代碼中,在一個(gè)類上添加@EnableScheduling注解,在方法上加上@Scheduled,配置下 cron 表達(dá)式,一個(gè)最最簡(jiǎn)單的cron定時(shí)任務(wù)就完成了。cron表達(dá)式的各個(gè)組成部分,可以參考下面:
@Scheduled(cron = "[Seconds] [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]")
2、fixedRate和fixedDelay
@Scheduled注解除了cron表達(dá)式,還有其他配置方式,比如fixedRate和fixedDelay,下面這個(gè)示例通過(guò)配置方式的不同,實(shí)現(xiàn)不同形式的定時(shí)任務(wù)調(diào)度,示例代碼如下:
package com.power.demo.scheduledtask.simple; import com.power.demo.util.DateTimeUtil; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component @EnableScheduling public class SpringTaskB { /*fixedRate:上一次開始執(zhí)行時(shí)間點(diǎn)之后5秒再執(zhí)行*/ @Scheduled(fixedRate = 5000) public void timerFixedRate() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(fixedRate)現(xiàn)在時(shí)間:%s", DateTimeUtil.fmtDate(new Date()))); } /*fixedDelay:上一次執(zhí)行完畢時(shí)間點(diǎn)之后5秒再執(zhí)行*/ @Scheduled(fixedDelay = 5000) public void timerFixedDelay() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(fixedDelay)現(xiàn)在時(shí)間:%s", DateTimeUtil.fmtDate(new Date()))); } /*第一次延遲2秒后執(zhí)行,之后按fixedDelay的規(guī)則每5秒執(zhí)行一次*/ @Scheduled(initialDelay = 2000, fixedDelay = 5000) public void timerInitDelay() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(initDelay)現(xiàn)在時(shí)間:%s", DateTimeUtil.fmtDate(new Date()))); } } SpringTaskB
注意一下主要區(qū)別:
@Scheduled(fixedRate = 5000)
:上一次開始執(zhí)行時(shí)間點(diǎn)之后5秒再執(zhí)行
@Scheduled(fixedDelay = 5000)
:上一次執(zhí)行完畢時(shí)間點(diǎn)之后5秒再執(zhí)行
@Scheduled(initialDelay=2000, fixedDelay=5000)
:第一次延遲2秒后執(zhí)行,之后按fixedDelay的規(guī)則每5秒執(zhí)行一次
有時(shí)候,很多項(xiàng)目我們都需要配置好定時(shí)任務(wù)后立即執(zhí)行一次,initialDelay就可以不用配置了。
3、zone
@Scheduled注解還有一個(gè)熟悉的屬性zone,表示時(shí)區(qū),通常,如果不寫,定時(shí)任務(wù)將使用服務(wù)器的默認(rèn)時(shí)區(qū);如果你的任務(wù)想在特定時(shí)區(qū)特定時(shí)間點(diǎn)跑起來(lái),比如常見的多語(yǔ)言系統(tǒng)可能會(huì)定時(shí)跑腳本更新數(shù)據(jù),就可以設(shè)置一個(gè)時(shí)區(qū),如東八區(qū),就可以設(shè)置為:
zone = "GMT+8:00"
二、Quartz
Quartz是應(yīng)用最為廣泛的開源任務(wù)調(diào)度框架之一,有很多公司都根據(jù)它實(shí)現(xiàn)自己的定時(shí)任務(wù)管理系統(tǒng)。Quartz提供了最常用的兩種定時(shí)任務(wù)觸發(fā)器,即SimpleTrigger和CronTrigger,本文以最廣泛使用的CronTrigger為例。
1、添加依賴
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
2、配置cron表達(dá)式
示例代碼需要,在application.properties文件中新增如下配置:
## Quartz定時(shí)job配置 job.taska.cron=*/3 * * * * ? job.taskb.cron=*/7 * * * * ? job.taskmail.cron=*/5 * * * * ?
其實(shí),我們完全可以不用配置,直接在代碼里面寫或者持久化在DB中然后讀取也可以。
3、添加定時(shí)任務(wù)實(shí)現(xiàn)
任務(wù)1:
package com.power.demo.scheduledtask.quartz; import com.power.demo.util.DateTimeUtil; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.util.Date; @DisallowConcurrentExecution public class QuartzTaskA implements Job { @Override public void execute(JobExecutionContext var1) throws JobExecutionException { try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(QuartzTaskA)%s 每隔3秒執(zhí)行一次,記錄日志", DateTimeUtil.fmtDate(new Date()))); } } QuartzTaskA
任務(wù)2:
package com.power.demo.scheduledtask.quartz; import com.power.demo.util.DateTimeUtil; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.util.Date; @DisallowConcurrentExecution public class QuartzTaskB implements Job { @Override public void execute(JobExecutionContext var1) throws JobExecutionException { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } System.out.println(String.format("(QuartzTaskB)%s 每隔7秒執(zhí)行一次,記錄日志", DateTimeUtil.fmtDate(new Date()))); } } QuartzTaskB
定時(shí)發(fā)送郵件任務(wù):
package com.power.demo.scheduledtask.quartz; import com.power.demo.service.contract.MailService; import com.power.demo.util.DateTimeUtil; import com.power.demo.util.PowerLogger; import org.joda.time.DateTime; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; @DisallowConcurrentExecution public class MailSendTask implements Job { @Autowired private MailService mailService; @Override public void execute(JobExecutionContext var1) throws JobExecutionException { System.out.println(String.format("(MailSendTask)%s 每隔5秒發(fā)送郵件", DateTimeUtil.fmtDate(new Date()))); try { //Thread.sleep(1); DateTime dtNow = new DateTime(new Date()); Date startTime = dtNow.minusMonths(1).toDate();//一個(gè)月前 Date endTime = dtNow.plusDays(1).toDate(); mailService.autoSend(startTime, endTime); PowerLogger.info(String.format("發(fā)送郵件,開始時(shí)間:%s,結(jié)束時(shí)間:%s" , DateTimeUtil.fmtDate(startTime), DateTimeUtil.fmtDate(endTime))); } catch (Exception e) { e.printStackTrace(); PowerLogger.info(String.format("發(fā)送郵件,出現(xiàn)異常:%s,結(jié)束時(shí)間:%s", e)); } } } MailSendTask
實(shí)現(xiàn)任務(wù)看上去非常簡(jiǎn)單,繼承Quartz的Job接口,重寫execute方法即可。
4、集成Quartz定時(shí)任務(wù)
怎么讓Spring自動(dòng)識(shí)別初始化Quartz定時(shí)任務(wù)實(shí)例呢?這就需要引用Spring管理的Bean,向Spring容器暴露所必須的bean,通過(guò)定義Job Factory實(shí)現(xiàn)自動(dòng)注入。
首先,添加Spring注入的Job Factory類:
package com.power.demo.scheduledtask.quartz.config; import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.scheduling.quartz.SpringBeanJobFactory; public final class AutowireBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; /** * Spring提供了一種機(jī)制讓你可以獲取ApplicationContext,即ApplicationContextAware接口 * 對(duì)于一個(gè)實(shí)現(xiàn)了ApplicationContextAware接口的類,Spring會(huì)實(shí)例化它的同時(shí)調(diào)用它的 * public voidsetApplicationContext(ApplicationContext applicationContext) throws BeansException;接口, * 將該bean所屬上下文傳遞給它。 **/ @Override public void setApplicationContext(final ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; } } AutowireBeanJobFactory
定義QuartzConfig:
package com.power.demo.scheduledtask.quartz.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration public class QuartzConfig { @Autowired @Qualifier("quartzTaskATrigger") private CronTriggerFactoryBean quartzTaskATrigger; @Autowired @Qualifier("quartzTaskBTrigger") private CronTriggerFactoryBean quartzTaskBTrigger; @Autowired @Qualifier("mailSendTrigger") private CronTriggerFactoryBean mailSendTrigger; //Quartz中的job自動(dòng)注入spring容器托管的對(duì)象 @Bean public AutowireBeanJobFactory autoWiringSpringBeanJobFactory() { return new AutowireBeanJobFactory(); } @Bean public SchedulerFactoryBean schedulerFactoryBean() { SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setJobFactory(autoWiringSpringBeanJobFactory()); //配置Spring注入的Job類 //設(shè)置CronTriggerFactoryBean,設(shè)定任務(wù)Trigger scheduler.setTriggers( quartzTaskATrigger.getObject(), quartzTaskBTrigger.getObject(), mailSendTrigger.getObject() ); return scheduler; } } QuartzConfig
接著配置job明細(xì):
package com.power.demo.scheduledtask.quartz.config; import com.power.demo.common.AppField; import com.power.demo.scheduledtask.quartz.MailSendTask; import com.power.demo.scheduledtask.quartz.QuartzTaskA; import com.power.demo.scheduledtask.quartz.QuartzTaskB; import com.power.demo.util.ConfigUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.JobDetailFactoryBean; @Configuration public class TaskSetting { @Bean(name = "quartzTaskA") public JobDetailFactoryBean jobDetailAFactoryBean() { //生成JobDetail JobDetailFactoryBean factory = new JobDetailFactoryBean(); factory.setJobClass(QuartzTaskA.class); //設(shè)置對(duì)應(yīng)的Job factory.setGroup("quartzTaskGroup"); factory.setName("quartzTaskAJob"); factory.setDurability(false); factory.setDescription("測(cè)試任務(wù)A"); return factory; } @Bean(name = "quartzTaskATrigger") public CronTriggerFactoryBean cronTriggerAFactoryBean() { String cron = ConfigUtil.getConfigVal(AppField.JOB_TASKA_CRON); CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean(); //設(shè)置JobDetail stFactory.setJobDetail(jobDetailAFactoryBean().getObject()); stFactory.setStartDelay(1000); stFactory.setName("quartzTaskATrigger"); stFactory.setGroup("quartzTaskGroup"); stFactory.setCronExpression(cron); return stFactory; } @Bean(name = "quartzTaskB") public JobDetailFactoryBean jobDetailBFactoryBean() { //生成JobDetail JobDetailFactoryBean factory = new JobDetailFactoryBean(); factory.setJobClass(QuartzTaskB.class); //設(shè)置對(duì)應(yīng)的Job factory.setGroup("quartzTaskGroup"); factory.setName("quartzTaskBJob"); factory.setDurability(false); factory.setDescription("測(cè)試任務(wù)B"); return factory; } @Bean(name = "quartzTaskBTrigger") public CronTriggerFactoryBean cronTriggerBFactoryBean() { String cron = ConfigUtil.getConfigVal(AppField.JOB_TASKB_CRON); CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean(); //設(shè)置JobDetail stFactory.setJobDetail(jobDetailBFactoryBean().getObject()); stFactory.setStartDelay(1000); stFactory.setName("quartzTaskBTrigger"); stFactory.setGroup("quartzTaskGroup"); stFactory.setCronExpression(cron); return stFactory; } @Bean(name = "mailSendTask") public JobDetailFactoryBean jobDetailMailFactoryBean() { //生成JobDetail JobDetailFactoryBean factory = new JobDetailFactoryBean(); factory.setJobClass(MailSendTask.class); //設(shè)置對(duì)應(yīng)的Job factory.setGroup("quartzTaskGroup"); factory.setName("mailSendTaskJob"); factory.setDurability(false); factory.setDescription("郵件發(fā)送任務(wù)"); return factory; } @Bean(name = "mailSendTrigger") public CronTriggerFactoryBean cronTriggerMailFactoryBean() { String cron = ConfigUtil.getConfigVal(AppField.JOB_TASKMAIL_CRON); CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean(); //設(shè)置JobDetail stFactory.setJobDetail(jobDetailMailFactoryBean().getObject()); stFactory.setStartDelay(1000); stFactory.setName("mailSendTrigger"); stFactory.setGroup("quartzTaskGroup"); stFactory.setCronExpression(cron); return stFactory; } } TaskSetting
最后啟動(dòng)你的Spring Boot定時(shí)任務(wù)應(yīng)用,一個(gè)完整的基于Quartz調(diào)度的定時(shí)任務(wù)就實(shí)現(xiàn)好了。
本文定時(shí)任務(wù)示例中,有一個(gè)定時(shí)發(fā)送郵件任務(wù)MailSendTask,下一篇將分享Spring Boot應(yīng)用中以MongoDB作為存儲(chǔ)介質(zhì)的簡(jiǎn)易郵件系統(tǒng)。
擴(kuò)展閱讀:
很多公司都會(huì)有自己的定時(shí)任務(wù)調(diào)度框架和系統(tǒng),在Spring Boot中如何整合Quartz集群,實(shí)現(xiàn)動(dòng)態(tài)定時(shí)任務(wù)配置?
參考:
http://www.dbjr.com.cn/article/139591.htm
http://www.dbjr.com.cn/article/139597.htm
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- SpringBoot定時(shí)任務(wù)兩種(Spring Schedule 與 Quartz 整合 )實(shí)現(xiàn)方法
- 詳解Spring Boot中使用@Scheduled創(chuàng)建定時(shí)任務(wù)
- 詳解SpringBoot 創(chuàng)建定時(shí)任務(wù)(配合數(shù)據(jù)庫(kù)動(dòng)態(tài)執(zhí)行)
- 詳解Spring Boot 定時(shí)任務(wù)的實(shí)現(xiàn)方法
- spring-boot通過(guò)@Scheduled配置定時(shí)任務(wù)及定時(shí)任務(wù)@Scheduled注解的方法
- SpringBoot 定時(shí)任務(wù)遇到的坑
- springboot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置定時(shí)任務(wù)的方法
- springboot整合quartz實(shí)現(xiàn)定時(shí)任務(wù)示例
- spring boot整合quartz實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)的方法
- 詳解SpringBoot開發(fā)案例之整合定時(shí)任務(wù)(Scheduled)
相關(guān)文章
深入了解Java中Synchronized關(guān)鍵字的實(shí)現(xiàn)原理
synchronized是JVM的內(nèi)置鎖,基于Monitor機(jī)制實(shí)現(xiàn),每一個(gè)對(duì)象都有一個(gè)與之關(guān)聯(lián)的監(jiān)視器?(Monitor),這個(gè)監(jiān)視器充當(dāng)了一種互斥鎖的角色,本文就詳細(xì)聊一聊Synchronized關(guān)鍵字的實(shí)現(xiàn)原理,需要的朋友可以參考下2023-06-06java中Supplier知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于java中Supplier知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-04-04JVM調(diào)優(yōu)OutOfMemoryError異常分析
這篇文章主要為大家介紹了JVM調(diào)優(yōu)OutOfMemoryError異常分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11java8中的lambda表達(dá)式,看這篇絕對(duì)夠
這篇文章主要介紹了java8中的lambda表達(dá)式,看這篇絕對(duì)夠!具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot集成JWT實(shí)現(xiàn)Token登錄驗(yàn)證的示例代碼
隨著技術(shù)的發(fā)展,分布式web應(yīng)用的普及,通過(guò)session管理用戶登錄狀態(tài)成本越來(lái)越高,因此慢慢發(fā)展成為token的方式做登錄身份校驗(yàn),本文就來(lái)介紹一下SpringBoot集成JWT實(shí)現(xiàn)Token登錄驗(yàn)證的示例代碼,感興趣的可以了解一下2023-12-12一篇文章帶你深入理解JVM虛擬機(jī)讀書筆記--鎖優(yōu)化
這篇文章深入介紹了JVM虛擬機(jī)的鎖優(yōu)化,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2021-09-09Spring?Boot?實(shí)現(xiàn)?WebSocket?的代碼示例
WebSocket?協(xié)議是獨(dú)立的基于?TCP?協(xié)議。它與?HTTP?的唯一關(guān)系是,它的握手會(huì)被?HTTP?服務(wù)器解釋為?Upgrade?請(qǐng)求,接下來(lái)通過(guò)本文給大家介紹Spring?Boot?實(shí)現(xiàn)?WebSocket?示例詳解,需要的朋友可以參考下2022-04-04