網上查了許多關於springboot與quartz資料,發現使用XML配置的很少,簡單整理了下,算是定時任務入門參考吧。
- 在pom.xml文件中,添加配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
- 創建任務定時處理類 SysDataJob
package service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; @Service public class SysDataJob { private final Log log = LogFactory.getLog(SysDataJob.class); public void deleteInfo() { log.info("Job start"); System.out.println("Job 數據處理"); } }
- 在resources文件下,創建quartz-config.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--定時刪除數據庫數據任務--> <!-- 配置Job類 --> <bean id="sysDataJob" class="service.SysDataJob"></bean> <!-- 配置JobDetail --> <bean id="springQtzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 執行目標job --> <property name="targetObject" ref="sysDataJob"></property> <!-- 要執行的方法 --> <property name="targetMethod" value="deleteInfo"></property> <property name="concurrent" value="false"></property><!--配置為false不允許任務並發執行--> </bean> <!-- 配置tirgger觸發器 --> <bean id="cronTrigger1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <!-- jobDetail --> <property name="jobDetail" ref="springQtzJob"></property> <!-- cron表達式,執行時間每10秒執行一次 --> <!-- 可以根據自己的需求指定執行時間 --> <property name="cronExpression" value="0/10 0/1 0/1 * * ? "></property> </bean> <!-- 配置調度工廠 --> <bean id="springJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger1"></ref> <!-- <ref bean="cronTrigger2"></ref>--> </list> </property> </bean> </beans>
在應用程序啟動時,添加注解,指定xml路徑 @ImportResource("classpath:quartz-config.xml")
package com.howdy.quartzsimple; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; @SpringBootApplication @ImportResource("classpath:quartz-config.xml") public class QuartzSimpleApplication { public static void main(String[] args) { SpringApplication.run(QuartzSimpleApplication.class, args); } }
- 完整的目錄結構,最后打印日志,是每10秒執行一次
源碼下載:https://download.csdn.net/download/haojuntu/13184110

