[java]spring整合quartz定時任務
阿新 • • 發佈:2018-12-02
quartz適合單系統定時任務,分散式不適合,廢話少說開始 使用
1.
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.3</version> </dependency>
2.spring-quartz.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context/spring-context.xsd " default-autowire="byType"> <bean id="biCronJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="biTaskCronService" /> <property name="targetMethod" value="run" /> <property name="concurrent" value="false" /> <property name="arguments"> <list></list> </property> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="biCronJob" /> <property name="cronExpression" value="0 */5 * * * ?" /> </bean> <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire="no"> <property name="triggers"> <list> <ref bean="cronTrigger" /> </list> </property> </bean> </beans>
3程式碼展示
/** * @author :dongshuo * @date : 2018/10/13 16:00 * @desc : 定時執行任務 */ @Service("biTaskCronService") public class BiTaskCronService implements Runnable { private static final Logger logger = LoggerFactory.getLogger(BiTaskCronService.class); @Autowired TBiTaskAction tBiTaskAction; @Override public void run() { try { logger.info("BiTaskCronService run"); tBiTaskAction.startTask(); } catch (Exception e) { logger.error("BiTaskCronService exception",e); } } }