springboot定時(shí)任務(wù)詳解
在我們開(kāi)發(fā)項(xiàng)目過(guò)程中,經(jīng)常需要定時(shí)任務(wù)來(lái)幫助我們來(lái)做一些內(nèi)容, Spring Boot 默認(rèn)已經(jīng)幫我們實(shí)行了,只需要添加相應(yīng)的注解就可以實(shí)現(xiàn)
一、基于注解(靜態(tài))1、pom 包配置pom 包里面只需要引入 Spring Boot Starter 包即可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>2、創(chuàng)建定時(shí)任務(wù)實(shí)現(xiàn)類(lèi)
定時(shí)任務(wù)1:
@Configuration@EnableSchedulingpublic class SchedulerTask { private int count=0; @Scheduled(cron='*/6 * * * * ?') private void process(){ System.out.println('this is scheduler task runing '+(count++)); }}
定時(shí)任務(wù)2:
@Configuration@EnableSchedulingpublic class Scheduler2Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat('HH:mm:ss'); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println('現(xiàn)在時(shí)間:' + dateFormat.format(new Date())); }}
結(jié)果如下:
this is scheduler task runing 0現(xiàn)在時(shí)間:09:44:17this is scheduler task runing 1現(xiàn)在時(shí)間:09:44:23this is scheduler task runing 2現(xiàn)在時(shí)間:09:44:29this is scheduler task runing 3現(xiàn)在時(shí)間:09:44:35參數(shù)說(shuō)明
@Configuration用于標(biāo)記配置類(lèi),兼?zhèn)銫omponent的效果。
@EnableScheduling表示開(kāi)啟定時(shí)任務(wù)
@Scheduled 參數(shù)可以接受兩種定時(shí)的設(shè)置,一種是我們常用的cron='*/6 * * * * ?',一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內(nèi)容。
fixedRate 說(shuō)明
@Scheduled(fixedRate = 6000) :上一次開(kāi)始執(zhí)行時(shí)間點(diǎn)之后6秒再執(zhí)行
@Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后6秒再執(zhí)行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執(zhí)行,之后按 fixedRate 的規(guī)則每6秒執(zhí)行一次
cron屬性,通過(guò)表達(dá)式形式指定任務(wù)執(zhí)行規(guī)則,同樣也是從上一次任務(wù)執(zhí)行完畢開(kāi)始計(jì)時(shí)。表達(dá)式規(guī)則如下:
每個(gè)位置的規(guī)則如下:
備注:
星號(hào)(*):可用在所有字段中,表示對(duì)應(yīng)時(shí)間域的每一個(gè)時(shí)刻,例如,*在分鐘字段時(shí),表示“每分鐘”。 問(wèn)號(hào)(?):該字符只在日期和星期字段中使用,它通常指定為“無(wú)意義的值”,相當(dāng)于占位符。 減號(hào)(-):表達(dá)一個(gè)范圍,如在小時(shí)字段中使用“10-12”,則表示從10到12點(diǎn),即10,11,12。 逗號(hào)(,):表達(dá)一個(gè)列表值,如在星期字段中使用“MON,WED,FRI”,則表示星期一,星期三和星期五。 斜杠(/):x/y表達(dá)一個(gè)等步長(zhǎng)序列,x為起始值,y為增量步長(zhǎng)值。如在秒數(shù)字段中使用0/15,則表示為0,15,30和45秒,而5/15在分鐘字段中表示5,20,35,50,你也可以使用*/y,它等同于0/y。 L:該字符只在日期和星期字段中使用,代表“Last”的意思,但它在兩個(gè)字段中意思不同。L在日期字段中,表示這個(gè)月份的最后一天,如一月的31號(hào),非閏年二月的28號(hào);如果L用在星期中,則表示星期六,等同于7。但是,如果L出現(xiàn)在星期字段里,而且在前面有一個(gè)數(shù)值X,則表示“這個(gè)月的最后X天”,例如,6L表示該月的最后星期五。 W:該字符只能出現(xiàn)在日期字段里,是對(duì)前導(dǎo)日期的修飾,表示離該日期最近的工作日。例如15W表示離該月15號(hào)最近的工作日,如果該月15號(hào)是星期六,則匹配14號(hào)星期五;如果15日是星期日,則匹配16號(hào)星期一;如果15號(hào)是星期二,那結(jié)果就是15號(hào)星期二。但必須注意關(guān)聯(lián)的匹配日期不能夠跨月,如你指定1W,如果1號(hào)是星期六,結(jié)果匹配的是3號(hào)星期一,而非上個(gè)月最后的那天。W字符串只能指定單一日期,而不能指定日期范圍。 LW組合:在日期字段可以組合使用LW,它的意思是當(dāng)月的最后一個(gè)工作日。 井號(hào)(#):該字符只能在星期字段中使用,表示當(dāng)月某個(gè)工作日。如6#3表示當(dāng)月的第三個(gè)星期五(6表示星期五,#3表示當(dāng)前的第三個(gè)),而4#5表示當(dāng)月的第五個(gè)星期三,假設(shè)當(dāng)月沒(méi)有第五個(gè)星期三,忽略不觸發(fā)。 C:該字符只在日期和星期字段中使用,代表“Calendar”的意思。它的意思是計(jì)劃所關(guān)聯(lián)的日期,如果日期沒(méi)有被關(guān)聯(lián),則相當(dāng)于日歷中所有日期。例如5C在日期字段中就相當(dāng)于日歷5日以后的第一天。1C在星期字段中相當(dāng)于星期日后的第一天。 cron表達(dá)式對(duì)大小寫(xiě)不敏感。 二、基于接口(動(dòng)態(tài))1、pom包配置<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId></dependency>2、添加數(shù)據(jù)庫(kù)記錄:
開(kāi)啟本地?cái)?shù)據(jù)庫(kù)mysql,隨便打開(kāi)查詢窗口,然后執(zhí)行腳本內(nèi)容,如下:
DROP DATABASE IF EXISTS `socks`;CREATE DATABASE `socks`;USE `SOCKS`;DROP TABLE IF EXISTS `cron`;CREATE TABLE `cron` ( `cron_id` varchar(30) NOT NULL PRIMARY KEY, `cron` varchar(30) NOT NULL );INSERT INTO `cron` VALUES (’1’, ’0/5 * * * * ?’);
然后在application.properties文件添加數(shù)據(jù)源
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/socks?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=falsespring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver3、創(chuàng)建定時(shí)器
數(shù)據(jù)庫(kù)準(zhǔn)備好數(shù)據(jù)之后,我們編寫(xiě)定時(shí)任務(wù),注意這里添加的是TriggerTask,目的是循環(huán)讀取我們?cè)跀?shù)據(jù)庫(kù)設(shè)置好的執(zhí)行周期,以及執(zhí)行相關(guān)定時(shí)任務(wù)的內(nèi)容。 具體代碼如下:
package com.cn.service;import com.cn.dao.CronMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskRegistrar;import org.springframework.scheduling.support.CronTrigger;import org.springframework.util.StringUtils;import java.time.LocalDateTime;@Configuration //1.主要用于標(biāo)記配置類(lèi),兼?zhèn)銫omponent的效果。@EnableScheduling // 2.開(kāi)啟定時(shí)任務(wù)public class DynamicScheduleTask implements SchedulingConfigurer { @Autowired private CronMapper cronMapper; /** * 執(zhí)行定時(shí)任務(wù). */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask(//1.添加任務(wù)內(nèi)容(Runnable)() -> System.out.println('執(zhí)行動(dòng)態(tài)定時(shí)任務(wù): ' + LocalDateTime.now().toLocalTime()),//2.設(shè)置執(zhí)行周期(Trigger)triggerContext -> { //2.1 從數(shù)據(jù)庫(kù)獲取執(zhí)行周期 String cron = cronMapper.selectByPrimaryKey('1').getCron(); //2.2 合法性校驗(yàn). if (StringUtils.isEmpty(cron)) { // Omitted Code .. } //2.3 返回執(zhí)行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext);} ); }}4、啟動(dòng)測(cè)試
然后打開(kāi)Navicat ,將執(zhí)行周期修改為每10秒執(zhí)行一次,查看控制臺(tái),發(fā)現(xiàn)執(zhí)行周期已經(jīng)改變,并且不需要我們重啟應(yīng)用,十分方便。如圖:
Quartz是OpenSymphony開(kāi)源組織在Job scheduling領(lǐng)域又一個(gè)開(kāi)源項(xiàng)目,它可以與J2EE與J2SE應(yīng)用程序相結(jié)合也可以單獨(dú)使用。Quartz可以用來(lái)創(chuàng)建簡(jiǎn)單或?yàn)檫\(yùn)行十個(gè),百個(gè),甚至是好幾萬(wàn)個(gè)Jobs這樣復(fù)雜的程序。
1.添加依賴<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId></dependency>2、編寫(xiě)任務(wù)類(lèi)
package com.cn.service; import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.quartz.QuartzJobBean;public class MyQuartz extends QuartzJobBean { private final Logger log = LoggerFactory.getLogger(MyQuartz.class); @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info('hello quartz'); } }3、編寫(xiě)配置類(lèi)
package com.cn.config;import com.cn.service.MyQuartz;import org.quartz.*;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; @Configurationpublic class QuartzConfig { @Bean public JobDetail myQuartz() { return JobBuilder.newJob(MyQuartz.class).withIdentity('MyQuartz').storeDurably().build(); } @Bean public Trigger studentRankQuartzTrigger() { return TriggerBuilder.newTrigger().forJob(myQuartz()).withIdentity('MyQuartz').withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule().withInterval(5, DateBuilder.IntervalUnit.SECOND)).build(); }}4、啟動(dòng)項(xiàng)目
每隔5秒打印一次'hello quartz'
以上就是springboot定時(shí)任務(wù)詳解的詳細(xì)內(nèi)容,更多關(guān)于springboot定時(shí)任務(wù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟2. Idea 快速生成方法返回值的操作3. 基于javascript處理二進(jìn)制圖片流過(guò)程詳解4. Docker 部署 Prometheus的安裝詳細(xì)教程5. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)6. ajax請(qǐng)求添加自定義header參數(shù)代碼7. idea開(kāi)啟代碼提示功能的方法步驟8. idea刪除項(xiàng)目的操作方法9. JAVA上加密算法的實(shí)現(xiàn)用例10. JS sort方法基于數(shù)組對(duì)象屬性值排序
