定时任务

        企业里业务场景经常需要用到定时任务,比如要定时向其他系统推送数据库工单或者账单信息,让其完成每日对账。

        下面来介绍自己的实际应用。

        常用的定时任务的实现方式大概有3种。我们企业目前仅仅只是用spring自带的quartz框架来实现的。这种实现方式需要继承一个类,感觉不够灵活。

        下面介绍这3种方式的具体实现方式。


        1.第一种方式:通过继承 org.springframework.scheduling.quartz.QuartzJobBean 这个类的实现方式

package com.pab.timer;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.pab.pojo.ScffEnUserQuery;
import com.pab.service.ScffEnUserService;

/**
 * <p>Title: JobOne</p>
 * <p>Description: 继承QuartzJobBean的方式</p>
 * <p>Company: http://www.***china.com </p>
 * @author ZY
 * <p> Just go on !!!</p>
 * @date 2017年6月12日  下午11:07:33 
 * @version v1.0
 */
public class Job1 extends QuartzJobBean {
	public static final Logger LOGGER = LoggerFactory.getLogger(Job1.class);
	//private int timeout;	//调度工厂实例化之后经过timeout时间进行调度任务
	private static int i = 0;	//记录执行的次数

	private ScffEnUserService scffEnUserService;
	public void setScffEnUserService(ScffEnUserService scffEnUserService) {
		this.scffEnUserService = scffEnUserService;
	}

	/**
	 * <p>Description:要调度的方法(任务)放到此方法中执行调度</p>  
	 * @param context
	 * @throws JobExecutionException
	 */
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		LOGGER.info("=================================");
		LOGGER.info("第" + (++i) + "次执行调度Job1任务");
		LOGGER.info("执行Job1任务开始");
		dosomething(context);
		LOGGER.info("执行Job1任务完毕");
		LOGGER.info("=================================");
	}

	/**
	 * <p>Description:具体要执行的任务</p>  
	 * @param context
	 */
	private void dosomething(JobExecutionContext context) {
		int count = scffEnUserService.countByExample(new ScffEnUserQuery());
		LOGGER.info("Job1查询到的总记录数是:" + count);
		LOGGER.info("Job1从数据库查询到的序列为:userSeq=" + scffEnUserService.getUserSeq());
	}

}

        然后对应的配置文件如下:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
	http://www.springframework.org/schema/beans/spring-beans-3.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/context    
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<bean id="scffEnUserService" class="com.pab.service.serviceImpl.ScffEnUserServiceImpl"/>
	
	<bean id="jobOne" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass" value="com.pab.timer.Job1" />
		<!-- 是否永久性 -->
		<property name="durability" value="true" />
		<!-- 当Quartz服务被终止后,再次启动任务时是否要尝试回复执行之前未完成的所有任务(针对多任务) -->
		<property name="requestsRecovery" value="true" />
	</bean>

	<!-- jobOne对应的触发器 -->
	<bean id="jobOneTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="jobOne" />
		<!-- 每隔5秒执行一次 -->
		<!-- <property name="cronExpression" value="0/5 * * * *  ?" /> -->
		<!-- 每隔1分钟执行一次 -->
		<property name="cronExpression" value="0 0/1 * * *  ?" />
	</bean>

	<!-- Spring调度工厂 -->
	<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<!-- 配置数据源,能够在数据库里记录定时任务相关信息 -->
		<!-- <property name="dataSource" ref="dataSource"/> -->

		<!-- Spring管理的service需要放到这里,才能注入成功 -->
		<property name="schedulerContextAsMap">
			<map>
				<entry key="scffEnUserService" value-ref="scffEnUserService"/>
			</map> 
		</property>
		
		<!-- 必须   QuartzScheduler 定时任务延迟启动,应用启动完成后再初始化 SchedulerFactoryBean 工厂-->
		<property name="startupDelay" value="10"/>
		<property name="applicationContextSchedulerContextKey" value="applicationContexKey"/>
		
		<!-- 可选  QuartzScheduler 启动时更新已存在的Job,这样就不用每次修改targetObject后删除quartz_job_details表对应的记录了-->
		<property name="overwriteExistingJobs" value="true"/>
		<property name="configLocation" value="classpath:conf/properties/quartz.properties"/>
		<property name="autoStartup" value="true"/>
		<property name="triggers">
			<list>
				<ref bean="jobOneTrigger"/>
			</list>
		</property>
	</bean>
</beans>


        2.第二种方式:直接使用普通的类方式实现(基于quartz框架)

package com.pab.timer;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pab.pojo.ScffEnUserQuery;
import com.pab.service.ScffEnUserService;

/**
 * <p>Title: Job2.java</p>
 * <p>Description: 无需继承,普通pojo类的方式</p>
 * <p>Company: http://www.***china.com </p>
 * @author ZY
 * <p> Just go on !!!</p>
 * @date 2017年6月15日  下午12:16:57 
 * @version v1.0
 */
public class Job2 {
	private static final Logger LOGGER =LoggerFactory.getLogger(Job2.class);
	//private int timeout;	//调度工厂实例化之后经过timeout时间进行调度任务
	private static int i = 0;
	
	@Resource(name="scffEnUserService")
	private ScffEnUserService scffEnUserService;
	
	public void execute(){
		LOGGER.info("=================================");
		LOGGER.info("第" + (++i) + "次执行调度Job2任务");
		LOGGER.info("执行任务开始");
		dosomething();
		LOGGER.info("执行任务完毕");
		LOGGER.info("=================================");
	}
	
	/**
	 * <p>Description:具体要执行的任务</p>  
	 */
	private void dosomething() {
		int count = scffEnUserService.countByExample(new ScffEnUserQuery());
		LOGGER.info("Job2查询到的总记录数是:" + count);
		LOGGER.info("Job2从数据库查询到的序列为:userSeq=" + scffEnUserService.getUserSeq());
	}
}

        然后对应的配置文件如下:

<?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:p="http://www.springframework.org/schema/p"  
	xmlns:context="http://www.springframework.org/schema/context"   
	xmlns:tx="http://www.springframework.org/schema/tx"  
	xmlns:aop="http://www.springframework.org/schema/aop"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
	http://www.springframework.org/schema/beans/spring-beans-3.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/context    
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">  

	<bean id="jobTwo" class="com.pab.timer.Job2" />
	
	<bean id="jobTwoInvoker" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="jobTwo"/>
		<property name="targetMethod" value="execute"/>
	</bean>
	
	<bean id="jobTwoTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="jobTwoInvoker"/>
		<!-- 每隔5秒执行一次定时任务 -->
		<!-- <property name="cronExpression" value="0/5 * * * * ?"/> -->
		<!-- 每隔1分钟执行一次 -->
		<property name="cronExpression" value="0 0/1 * * * ?"/>
	</bean>
	
	<bean id="xmlSchedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="jobTwoTrigger"/>
			</list>
		</property>
	</bean>
</beans>


        3.第三种方式:通过注解的方式实现

package com.pab.timer;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.pab.pojo.ScffEnUserQuery;
import com.pab.service.ScffEnUserService;

/**
 * <p>Title: Job3.java</p>
 * <p>Description: 通过注解的方式来实现定时任务</p>
 * <p>Company: http://www.***china.com </p>
 * @author ZY
 * <p> Just go on !!!</p>
 * @date 2017年6月15日  下午1:58:01 
 * @version v1.0
 */
@Component
public class Job3 {
	public static final Logger LOGGER = LoggerFactory.getLogger(Job3.class);
	//private int timeout;	   //调度工厂实例化之后经过timeout时间进行调度任务
	private static int i = 0;  //记录执行的次数
	
	@Resource(name="scffEnUserService")
	private ScffEnUserService scffEnUserService;
	
	//@Scheduled(cron="0/5 * * * * ?")  //每隔5秒执行一次
	@Scheduled(cron="0 0/1 * * * ?")    //每隔1分钟执行一次
	public void execute(){
		LOGGER.info("=================================");
		LOGGER.info("第" + (++i) + "次执行调度Job3任务");
		LOGGER.info("执行任务开始");
		dosomething();
		LOGGER.info("执行任务完毕");
		LOGGER.info("=================================");
	}
	
	/**
	 * <p>Description:具体要执行的任务</p>  
	 */
	private void dosomething() {
		int count = scffEnUserService.countByExample(new ScffEnUserQuery());
		LOGGER.info("Job3查询到的总记录数是:" + count);
		LOGGER.info("Job3从数据库查询到的序列为:userSeq=" + scffEnUserService.getUserSeq());
	}
}

        对应的配置文件内容如下:

<?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:p="http://www.springframework.org/schema/p"  
	xmlns:context="http://www.springframework.org/schema/context"   
	xmlns:tx="http://www.springframework.org/schema/tx"  
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:task="http://www.springframework.org/schema/task"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
	http://www.springframework.org/schema/beans/spring-beans-3.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/task
	http://www.springframework.org/schema/task/spring-task-3.0.xsd   
	http://www.springframework.org/schema/context    
	http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
	
	
	<!-- 使用注解的形式执行定时任务必需以下两个配置 -->
	<!-- 1.配置自动扫描 -->
	<context:component-scan base-package="com.pab.timer"/>
	<!-- 2.配置注解驱动 -->
	<task:annotation-driven/>
	
</beans>


        使用spring整合junit做单元测试,代码如下:

package com.pab.test;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


/**
 * <p>Title: TestAll.java</p>
 * <p>Description: </p>
 * <p>Company: http://www.***china.com </p>
 * @author ZY
 * <p> Just go on !!!</p>
 * @date 2017年6月15日  下午2:33:43 
 * @version v1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:conf/spring/spring-quartz-old.xml","classpath:conf/spring/spring-quartz-new.xml","classpath:conf/spring/spring-quartz-annotation.xml","classpath:conf/spring/applicationContext-dao.xml","classpath:conf/spring/applicationContext-service.xml"})
@Rollback
public class TestAll {

	@Test
	public void testRunAll(){
		while(true){}
	}
}

测试结果如下图:



        或者也可以搭建一个简单的web应用启动后,定时任务就会按照设定的时间来重复执行。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值