您好,登錄后才能下訂單哦!
這篇“springboot創(chuàng)建的web項(xiàng)目如何整合Quartz框架”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“springboot創(chuàng)建的web項(xiàng)目如何整合Quartz框架”文章吧。
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ù)雜的程序。Jobs可以做成標(biāo)準(zhǔn)的Java組件或EJBs。Quartz的最新版本為Quartz 2.3.2。
quartz可以在某一個(gè)有規(guī)律的時(shí)間點(diǎn)干某件事,是一個(gè)任務(wù)調(diào)度框架,可以被集成到j(luò)ava的各種應(yīng)用中使用,quartz框架可以支持分布式任務(wù)處理
整體代碼結(jié)構(gòu)
導(dǎo)入依賴(lài)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
創(chuàng)建quartz_demo數(shù)據(jù)庫(kù),執(zhí)行tables_mysql_innodb.sql文件創(chuàng)建對(duì)應(yīng)表,下面是文件內(nèi)容
# # In your Quartz properties file, you'll need to set # org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate # # # By: Ron Cordell - roncordell # I didn't see this anywhere, so I thought I'd post it here. This is the script from Quartz to create the tables in a MySQL database, modified to use INNODB instead of MYISAM. DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS; DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS; DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE; DROP TABLE IF EXISTS QRTZ_LOCKS; DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS; DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS; DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS; DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS; DROP TABLE IF EXISTS QRTZ_TRIGGERS; DROP TABLE IF EXISTS QRTZ_JOB_DETAILS; DROP TABLE IF EXISTS QRTZ_CALENDARS; CREATE TABLE QRTZ_JOB_DETAILS( SCHED_NAME VARCHAR(120) NOT NULL, JOB_NAME VARCHAR(190) NOT NULL, JOB_GROUP VARCHAR(190) NOT NULL, DESCRIPTION VARCHAR(250) NULL, JOB_CLASS_NAME VARCHAR(250) NOT NULL, IS_DURABLE VARCHAR(1) NOT NULL, IS_NONCONCURRENT VARCHAR(1) NOT NULL, IS_UPDATE_DATA VARCHAR(1) NOT NULL, REQUESTS_RECOVERY VARCHAR(1) NOT NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, JOB_NAME VARCHAR(190) NOT NULL, JOB_GROUP VARCHAR(190) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(190) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_CRON_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, CRON_EXPRESSION VARCHAR(120) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_SIMPROP_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, STR_PROP_1 VARCHAR(512) NULL, STR_PROP_2 VARCHAR(512) NULL, STR_PROP_3 VARCHAR(512) NULL, INT_PROP_1 INT NULL, INT_PROP_2 INT NULL, LONG_PROP_1 BIGINT NULL, LONG_PROP_2 BIGINT NULL, DEC_PROP_1 NUMERIC(13,4) NULL, DEC_PROP_2 NUMERIC(13,4) NULL, BOOL_PROP_1 VARCHAR(1) NULL, BOOL_PROP_2 VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_BLOB_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_CALENDARS ( SCHED_NAME VARCHAR(120) NOT NULL, CALENDAR_NAME VARCHAR(190) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)) ENGINE=InnoDB; CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_FIRED_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(190) NOT NULL, TRIGGER_GROUP VARCHAR(190) NOT NULL, INSTANCE_NAME VARCHAR(190) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, SCHED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(190) NULL, JOB_GROUP VARCHAR(190) NULL, IS_NONCONCURRENT VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,ENTRY_ID)) ENGINE=InnoDB; CREATE TABLE QRTZ_SCHEDULER_STATE ( SCHED_NAME VARCHAR(120) NOT NULL, INSTANCE_NAME VARCHAR(190) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)) ENGINE=InnoDB; CREATE TABLE QRTZ_LOCKS ( SCHED_NAME VARCHAR(120) NOT NULL, LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (SCHED_NAME,LOCK_NAME)) ENGINE=InnoDB; CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY); CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP); CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP); CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME); CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP); CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE); CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE); CREATE INDEX IDX_QRTZ_T_N_G_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE); CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME); CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME); CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME); CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE); CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE); CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME); CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY); CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP); CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP); CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP); commit;
配置quartz
server: port: ${PORT:12011} servlet: session: timeout: 86400s # session有效期(xxx秒) cookie: http-only: false # 如果為true, 瀏覽器腳本將無(wú)法訪(fǎng)問(wèn)cookie secure: false # 如果為true, 則僅通過(guò)https連接發(fā)送cookie, http無(wú)法攜帶cookie context-path: # 程序上下文路徑配置 spring: application: name: quartz-demo aop: proxy-target-class: true auto: true datasource: url: jdbc:mysql://localhost:3306/quartz_demo username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver # 配置日期格式化 jackson: date-format: yyyy-MM-dd HH:mm:ss #時(shí)間戳統(tǒng)一轉(zhuǎn)換為指定格式 time-zone: GMT+8 # 時(shí)區(qū)修改為東8區(qū) quartz: # 將任務(wù)等保存化到數(shù)據(jù)庫(kù) job-store-type: jdbc # 程序結(jié)束時(shí)會(huì)等待quartz相關(guān)的內(nèi)容結(jié)束 wait-for-jobs-to-complete-on-shutdown: true # QuartzScheduler啟動(dòng)時(shí)更新己存在的Job,這樣就不用每次修改targetObject后刪除qrtz_job_details表對(duì)應(yīng)記錄 overwrite-existing-jobs: true properties: org: quartz: # scheduler相關(guān) scheduler: # scheduler的實(shí)例名 instanceName: scheduler instanceId: AUTO # 持久化相關(guān) jobStore: class: org.quartz.impl.jdbcjobstore.JobStoreTX driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate # 表示數(shù)據(jù)庫(kù)中相關(guān)表是QRTZ_開(kāi)頭的 tablePrefix: QRTZ_ useProperties: false # 配置集群 # 是否加入集群 isClustered: true # 容許的最大作業(yè)延長(zhǎng)時(shí)間 clusterCheckinInterval: 20000 # 線(xiàn)程池相關(guān) threadPool: class: org.quartz.simpl.SimpleThreadPool # 線(xiàn)程數(shù) threadCount: 10 # 線(xiàn)程優(yōu)先級(jí) threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true mybatis-plus: global-config: db-config: logic-delete-field: is_deleted logic-delete-value: 1 logic-not-delete-value: 0 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl logging: level: com.my.quartz: debug
添加sys_job表
CREATE TABLE `sys_job` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `job_id` varchar(100) DEFAULT NULL, `job_name` varchar(255) DEFAULT NULL, `job_group_name` varchar(255) DEFAULT NULL, `invoke_target` varchar(255) NOT NULL, `cron_expression` varchar(50) DEFAULT NULL, `misfire_policy` varchar(255) DEFAULT NULL COMMENT 'cron計(jì)劃策略0=默認(rèn),1=立即觸發(fā)執(zhí)行,2=觸發(fā)一次執(zhí)行,3=不觸發(fā)立即執(zhí)行', `status` varchar(10) DEFAULT NULL COMMENT '任務(wù)狀態(tài)(0正常 1暫停)', `concurrent` varchar(10) DEFAULT NULL COMMENT '是否并發(fā)執(zhí)行(0允許 1禁止)', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
寫(xiě)兩條數(shù)據(jù)
mapper層的xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.my.quartz.boot.mapper.SysJobMapper"> <resultMap id="BaseResultMap" type="com.my.quartz.boot.SysJob"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="job_id" jdbcType="VARCHAR" property="jobId" /> <result column="job_name" jdbcType="VARCHAR" property="jobName" /> <result column="job_group_name" jdbcType="VARCHAR" property="jobGroupName" /> <result column="invoke_target" jdbcType="VARCHAR" property="invokeTarget" /> <result column="cron_expression" jdbcType="VARCHAR" property="cronExpression" /> <result column="misfire_policy" jdbcType="VARCHAR" property="misfirePolicy" /> <result column="status" jdbcType="VARCHAR" property="status" /> <result column="concurrent" jdbcType="VARCHAR" property="concurrent" /> </resultMap> <sql id="Base_Column_List"> t.id, t.job_id jobId, t.job_name jobName, t.job_group_name jobGroupName, t.invoke_target invokeTarget, t.cron_expression cronExpression, t.misfire_policy misfirePolicy, t.status, t.concurrent </sql> </mapper>
mapper接口
/** * Auto Generated * * @author :Boy * @date :Created in 2022-06-18 * @description: * @modified By: */ public interface SysJobMapper extends BaseMapper<SysJob> { }
service接口
public interface SysJobService extends IService<SysJob> { }
service接口實(shí)現(xiàn)
@Service public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements SysJobService { @Autowired private Scheduler scheduler; @Autowired private ScheduleUtils scheduleUtils; /** * 項(xiàng)目啟動(dòng)時(shí),初始化定時(shí)器 * 主要是防止手動(dòng)修改數(shù)據(jù)庫(kù)導(dǎo)致未同步到定時(shí)任務(wù)處理(注:不能手動(dòng)修改數(shù)據(jù)庫(kù)ID和任務(wù)組名,否則會(huì)導(dǎo)致臟數(shù)據(jù)) */ @PostConstruct public void init() throws SchedulerException, TaskException { scheduler.clear(); List<SysJob> jobList = baseMapper.selectList(null); for (SysJob job : jobList) { scheduleUtils.createScheduleJob(scheduler, job); } } }
controller代碼
@RestController @RequestMapping("/job") public class SysJobController { @Resource private SysJobService sysJobService; @Resource private ScheduleUtils scheduleUtils; @Resource private Scheduler scheduler; @PostMapping("/add") public Object add(@RequestBody SysJob entity) throws SchedulerException, TaskException { sysJobService.save(entity); scheduleUtils.createScheduleJob(scheduler, entity); return "ok"; } }
ScheduleUtils 定時(shí)任務(wù)工具類(lèi)
/** * @Author ScholarTang * @Date 2021/7/15 下午3:50 * @Desc 定時(shí)任務(wù)工具類(lèi) */ @Component public class ScheduleUtils { @Autowired private Scheduler scheduler; /** * 構(gòu)建任務(wù)觸發(fā)對(duì)象 * * @param jobName * @param jobGroup * @return */ public TriggerKey getTriggerKey(String jobName, String jobGroup) { return TriggerKey.triggerKey(jobName, jobGroup); } /** * 構(gòu)建任務(wù)鍵對(duì)象 * * @param jobName * @param jobGroup * @return */ public JobKey getJobKey(String jobName, String jobGroup) { return JobKey.jobKey(jobName, jobGroup); } /** * 創(chuàng)建定時(shí)調(diào)度任務(wù) * * * @param scheduler * @param job * @throws SchedulerException * @throws TaskException */ public void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException { // 構(gòu)建job信息 String jobName = job.getJobId() + "_" + job.getJobName(); String jobGroupName = job.getJobGroupName(); //TODO 反射動(dòng)態(tài)獲取Job實(shí)現(xiàn)類(lèi) //構(gòu)建job實(shí)例 JobDetail jobDetail = JobBuilder.newJob(QuartzJobImpl.class) .withIdentity(getJobKey(jobName, jobGroupName)) .build(); jobDetail.getJobDataMap().put("QuartzJobExecutionData", job); // 表達(dá)式調(diào)度構(gòu)建器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); // 按新的cronExpression表達(dá)式構(gòu)建一個(gè)新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobName, jobGroupName)) .withSchedule(cronScheduleBuilder).build(); // 放入?yún)?shù),運(yùn)行時(shí)的方法可以獲取 jobDetail.getJobDataMap().put("QuartzJobExecutionData", job); // 判斷是否存在 if (scheduler.checkExists(getJobKey(jobName, jobGroupName))) { // 防止創(chuàng)建時(shí)存在數(shù)據(jù)問(wèn)題 先移除,然后在執(zhí)行創(chuàng)建操作 scheduler.deleteJob(getJobKey(jobName, jobGroupName)); } //創(chuàng)建定時(shí)任務(wù)調(diào)度 scheduler.scheduleJob(jobDetail, trigger); // 暫停任務(wù) 規(guī)定 0啟動(dòng) 1暫停 if (job.getStatus().equals("1")) { scheduler.pauseJob(getJobKey(jobName, jobGroupName)); } } /** * 刪除定時(shí)調(diào)度任務(wù) * * @param sysJob * @throws SchedulerException */ public void deleteScheduleJob(SysJob sysJob) throws SchedulerException { scheduler.deleteJob(getJobKey(sysJob.getJobId() + "_" + sysJob.getJobName(), sysJob.getJobGroupName())); } /** * 設(shè)置定時(shí)任務(wù)策略 * * @param sysJob * @param cronScheduleBuilder * @return */ public CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob sysJob, CronScheduleBuilder cronScheduleBuilder) throws TaskException { switch (sysJob.getMisfirePolicy()) { case "0": return cronScheduleBuilder; case "1": return cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires(); case "2": return cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed(); case "3": return cronScheduleBuilder.withMisfireHandlingInstructionDoNothing(); default: throw new TaskException("任務(wù)失敗策略 '" + sysJob.getMisfirePolicy() + "' 不能在cron計(jì)劃任務(wù)中使用", TaskException.Code.CONFIG_ERROR); } } }
創(chuàng)建一個(gè)Job實(shí)現(xiàn)類(lèi),只是一個(gè)簡(jiǎn)單實(shí)現(xiàn)類(lèi),沒(méi)有對(duì)方法添加參數(shù)
@Slf4j @Component public class QuartzJobImpl implements Job { @Autowired private ApplicationContext context; @SneakyThrows @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { SysJob sysJob = new SysJob(); BeanUtils.copyProperties(jobExecutionContext.getMergedJobDataMap().get("QuartzJobExecutionData"), sysJob); log.info("正在執(zhí)行任務(wù)"); String invokeTarget = sysJob.getInvokeTarget(); String beanName = invokeTarget.split("\\.")[0]; String methodName = invokeTarget.split("\\.")[1]; Object bean = context.getBean(beanName); Class<?> clazz = bean.getClass(); Method method = clazz.getMethod(methodName); method.invoke(bean); log.info("已結(jié)束任務(wù)"); System.out.println(); } }
創(chuàng)建最終任務(wù)執(zhí)行類(lèi),執(zhí)行函數(shù)級(jí)別的定時(shí)任務(wù),數(shù)據(jù)庫(kù)中的invoke_target是和這里放入spring中的名稱(chēng)相同的,quartz_target.hello最終執(zhí)行的函數(shù)就是hello函數(shù)
@Slf4j @Component("quartz_target") public class QuartzJobExe { @Resource private Scheduler scheduler; public void hello() throws Exception { System.out.println("[job]實(shí)例執(zhí)行...hello..." + System.currentTimeMillis()); } public void action() throws Exception { System.out.println("[job]實(shí)例執(zhí)行...action..." + System.currentTimeMillis()); } }
最終代碼結(jié)構(gòu)
啟動(dòng)spring boot之后的任務(wù)狀態(tài)
使用postman工具類(lèi)添加一個(gè)任務(wù)
然后在代碼中添加一個(gè)對(duì)應(yīng)的方法
重新啟動(dòng)springboot的運(yùn)行結(jié)果
以上就是關(guān)于“springboot創(chuàng)建的web項(xiàng)目如何整合Quartz框架”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(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)容。