Quartz與Spring集成(二)
阿新 • • 發佈:2018-04-25
extends one tailf .get ron getname spring集成 text IT
一、獲取quartz詳情jar
<!-- quartz 的jar --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency>
二、相關代碼案例
//Main.java啟動類
public class Main { public static void main(String[] args) { new ClassPathXmlApplicationContext("classpath:applicationContext-scheduler.xml"); } }
//MyJob任務類
publicclass MyJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println("myJob執行了............" + context.getTrigger().getKey().getName()); ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().getJobDataMap() .get("applicationContext"); System.out.println("獲取到的Spring容器是" + applicationContext); } }
//applicationContext-scheduler.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 定義任務bean --> <bean name="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <!-- 指定具體的job類 --> <property name="jobClass" value="com.bky_lzw.quartz.MyJob" /> <!-- 指定job的名稱 --> <property name="name" value="myJob" /> <!-- 指定job分組 --> <property name="group" value="jobs" /> <!-- 必須設置為true,如果為false,當沒有活動的觸發器與之關聯時會在調度器中刪除該任務 --> <property name="durability" value="true" /> <!-- 指定spring容器的key,如果不設定在job中的jobmap中是獲取不到spring容器的 --> <property name="applicationContextJobDataKey" value="applicationContext" /> </bean> <!-- 定義觸發器 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="myJobDetail" /> <!-- 每一分鐘執行一次 --> <property name="cronExpression" value="0/5 * * * * ?" /> </bean> <!-- 定義調度器 --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger" /> </list> </property> </bean> </beans>
Quartz與Spring集成(二)