Quartz定时任务框架实现简单的示例

前言

Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。Quartz的最新版本为Quartz 2.3.0。

本小白在做工程有个需求是这样的,提交一个订单,在超过10分钟未支付的情况就去把数据的提交记录删除。所以我们要设置一个定时器在我们的工程当中,比喻隔一段时间就去检索我们的数据库有没有超过十分钟还没支付的订单。




准备工作

编辑器:eclipse,
springMVC+spring+Hibernate项目。
这是本小白在做的工程。




实战

先导入jar包,jar包有链接在这里可下载。下载之后导入,然后一定一定检索jar包有无重复,我的发现有3个是重复,原则是留高版本删低版本的。
在这里插入图片描述





在业务层新建一个task包,任务包。
在这里插入图片描述




新建一个任务接口,并且新建一个任务接口。
在这里插入图片描述源码

package com.bdqn.it.service.task;

public interface MyTask {
	public void sayHello();
}





新建一个任务包的实现包并且新建任务实现类实现方法,这个方法打印“Hello”。这个方法我们等会配置定时器调用它。
在这里插入图片描述
在这里插入图片描述源码

package com.bdqn.it.service.task.impl;

import org.springframework.stereotype.Service;
import com.bdqn.it.service.task.MyTask;

@Service("mytask")
public class MyTaskImpl implements MyTask {

	@Override
	public void sayHello() {
		System.out.println("hello!");
	}
}





在项目的src目录下配置“applicationContext-task.xml”文件

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-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/tx
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/cache 
     http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">


	<!-- 控制行为,做什么 -->
	<bean id="hi"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
		p:targetObject-ref="mytask" 
		p:targetMethod="sayHello" 
		p:concurrent="false" />

	<!-- 控制时间,你打算什么时候做 -->
	<bean id="triger_hi"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"
		p:jobDetail-ref="hi" 
		p:cronExpression="0/3 * * * * ?" />
		
	<!-- 控制开关 -->
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="triger_hi" />
			</list>
		</property>
	</bean>
</beans>

在这里插入图片描述





然后我运行项目,发现我的控制台每隔几秒就打印一次Hello!说明已经成功了。
在这里插入图片描述

发布了26 篇原创文章 · 获赞 3 · 访问量 1427

猜你喜欢

转载自blog.csdn.net/CQWNB/article/details/103584671