quartz 定时任务

1.引入quartz类库


 com.springsource.org.quartz-1.6.2.jar


2.创建石英任务

 

	/**
	 * 使用spring集成的石英调度,动态生成日志表
	 */
	public class GenerateLogsTableTask extends QuartzJobBean {

		//
		private LogService logService ;
		
		public void setLogService(LogService logService) {
			this.logService = logService;
		}

		/**
		 * 执行任务
		 */
		protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
			String tableName =  LogUtil.generateLogTableName(1);
			String sql = "create table if not exists " + tableName + " like logs";
			logService.executeSQL(sql);
			System.out.println(tableName + " 生成了! " );
			
			tableName =  LogUtil.generateLogTableName(2);
			sql = "create table if not exists " + tableName + " like logs";
			logService.executeSQL(sql);
			System.out.println(tableName + " 生成了! " );
		}
	}


 

3.配置调度任务  [conf/schedules.xml]

	<?xml version="1.0"?>
	<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		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/context 
							http://www.springframework.org/schema/context/spring-context-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/aop 
							http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
		<!-- 任务明细bean,对石英任务包装 -->
		<bean id="jobDetailBean" class="org.springframework.scheduling.quartz.JobDetailBean">
			<property name="jobClass" value="cn.itcast.surveypark.schedule.GenerateLogsTableTask" />
			<property name="jobDataAsMap">
				<map>
					<entry key="logService" value-ref="logService" />
				</map>
			</property>
		</bean>
		
		<!-- cron触发器bean,设置任务的调度策略的 -->
		<bean id="cronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerBean">
			<property name="jobDetail" ref="jobDetailBean" />
			<!-- cron表达式 -->
			<property name="cronExpression">
				<value>0 0 0 15 * ?</value>
			</property>
		</bean>
		
		<!-- 调度器工厂bean,激活触发器,启动石英任务的 -->
		<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
			<property name="triggers">
				<ref bean="cronTriggerBean"/>
			</property>
		</bean>
	</beans>


 

4.配置web.xml文件,一同加载spring的所有配置文件

	<!-- 通过上下文参数指定spring配置文件的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:beans.xml,classpath:schedules.xml</param-value>
	</context-param>


5.修改时间,为触发任务接近的时间,比如2013-1-14 23:59:00秒
6.启动观察效果

 

 

你可能感兴趣的:(quartz 定时任务)