`
sundoctor
  • 浏览: 325583 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Quartz 在 Spring 中如何动态配置时间

阅读更多

在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度。
有关调度的实现我就第一就想到了Quartz这个开源调度组件,因为很多项目使用过,Spring结合Quartz静态配置调度任务时间,非常easy。比如:每天凌晨几点定时运行一个程序,这只要在工程中的spring配置文件中配置好spring整合quartz的几个属性就好。

Spring配置文件

<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="simpleService" />
<property name="targetMethod" value="test" />
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail" />
<property name="cronExpression" value="0 0/50 * ? * * *" />
</bean>
<bean  id="schedulerTrigger" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>     
</list>
</property>
</bean> 

 这种配置就是对quartz的一种简单的使用了,调度任务会在spring启动的时候加载到内存中,按照cronTrigger中定义的 cronExpression定义的时间按时触发调度任务。但是这是quartz使用“内存”方式的一种配置,也比较常见,当然对于不使用spring的项目,也可以单独整合quartz。方法也比较简单,可以从quartz的doc中找到配置方式,或者看一下《Quartz Job Scheduling Framework 》。

但是对于想持久化调度任务的状态,并且灵活调整调度时间的方式来说,上面的内存方式就不能满足要求了,正如本文开始我遇到的情况,需要采用数据库方式集成 Quartz,这部分集成其实在《Quartz Job Scheduling Framework 》中也有较为详细的介绍,当然doc文档中也有,但是缺乏和spring集成的实例。

一、需要构建Quartz数据库表,建表脚本在Quartz发行包的docs\dbTables目录,里面有各种数据库建表脚本,例子中采用的Quartz 2.2.1版本,使用H2内存数据库,执行了Quartz发行包的docs\dbTables\tables_h2.sql建表。

二、建立Maven project,完成后目录如下


 

三、配置applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="   
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   ">
    <context:component-scan base-package="com.sundoctor" />		
    <!-- 使用H2内存数据库并创建quartz数据库表 -->
    <jdbc:embedded-database id="dataSource" type="H2">
        <jdbc:script location="classpath:db/tables_h2.sql"/>       
    </jdbc:embedded-database>
</beans>

 
这里只是配置了数据库连接dataSource,为了简单方便,我使用H2内存数据库,执行tables_h2.sql创建quartz数据库表,还没有涉及到quartz有关配置,下面且听我慢慢道来。

四、实现动态定时任务
  什么是动态定时任务:是由客户制定生成的,服务端只知道该去执行什么任务,但任务的定时是不确定的(是由客户制定)。
这样总不能修改配置文件每定制个定时任务就增加一个trigger吧,即便允许客户修改配置文件,但总需要重新启动web服务啊,研究了下Quartz在Spring中的动态定时,发现

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail" />
<property name="cronExpression" value="0 0/50 * ? * * *" />
</bean> 

 

cronExpression是关键,如果可以动态设置cronExpression的值,就可以顺利解决问题了。这样我们就不能直接使用org.springframework.scheduling.quartz.CronTriggerFactoryBean,需要自己实现一个动态调度服务类,在其中构建CronTrigger或SimpleTrigger,动态配置时间。
动态调度服务接口:

package com.sundoctor.quartz.service;

import java.util.Date;

import org.quartz.CronExpression;

public interface SchedulerService {
	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param cronExpression
	 *            Quartz Cron 表达式,如 "0/10 * * ? * * *"等
	 */
	void schedule(String cronExpression);

	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param name
	 *            Quartz CronTrigger名称
	 * @param cronExpression
	 *            Quartz Cron 表达式,如 "0/10 * * ? * * *"等
	 */
	void schedule(String name, String cronExpression);

	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param name
	 *            Quartz CronTrigger名称
	 * @param group
	 *            Quartz CronTrigger组
	 * @param cronExpression
	 *            Quartz Cron 表达式,如 "0/10 * * ? * * *"等
	 */
	void schedule(String name, String group, String cronExpression);

	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param cronExpression
	 *            Quartz CronExpression
	 */
	void schedule(CronExpression cronExpression);

	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param name
	 *            Quartz CronTrigger名称
	 * @param cronExpression
	 *            Quartz CronExpression
	 */
	void schedule(String name, CronExpression cronExpression);

	/**
	 * 根据 Quartz Cron Expression 调试任务
	 * 
	 * @param name
	 *            Quartz CronTrigger名称
	 * @param group
	 *            Quartz CronTrigger组
	 * @param cronExpression
	 *            Quartz CronExpression
	 */
	void schedule(String name, String group, CronExpression cronExpression);

	/**
	 * 在startTime时执行调试一次
	 * 
	 * @param startTime
	 *            调度开始时间
	 */
	void schedule(Date startTime);

	void schedule(Date startTime, String group);

	/**
	 * 在startTime时执行调试一次
	 * 
	 * @param name
	 *            Quartz SimpleTrigger 名称
	 * @param startTime
	 *            调度开始时间
	 */
	void schedule(String name, Date startTime);

	void schedule(String name, Date startTime, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度
	 * 
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 */
	void schedule(Date startTime, Date endTime);

	void schedule(Date startTime, Date endTime, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度
	 * 
	 * @param name
	 *            Quartz SimpleTrigger 名称
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 */
	void schedule(String name, Date startTime, Date endTime);

	void schedule(String name, Date startTime, Date endTime, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次
	 * 
	 * @param startTime
	 *            调度开始时间
	 * @param repeatCount
	 *            重复执行次数
	 */
	void schedule(Date startTime, int repeatCount);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次
	 * 
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 * @param repeatCount
	 *            重复执行次数
	 */
	void schedule(Date startTime, Date endTime, int repeatCount);

	void schedule(Date startTime, Date endTime, int repeatCount, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次
	 * 
	 * @param name
	 *            Quartz SimpleTrigger 名称
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 * @param repeatCount
	 *            重复执行次数
	 */
	void schedule(String name, Date startTime, Date endTime, int repeatCount);

	void schedule(String name, Date startTime, Date endTime, int repeatCount, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次,每隔repeatInterval秒执行一次
	 * 
	 * @param startTime
	 *            调度开始时间
	 * 
	 * @param repeatCount
	 *            重复执行次数
	 * @param repeatInterval
	 *            执行时间隔间
	 */
	void schedule(Date startTime, int repeatCount, long repeatInterval);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次,每隔repeatInterval秒执行一次
	 * 
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 * @param repeatCount
	 *            重复执行次数
	 * @param repeatInterval
	 *            执行时间隔间
	 */
	void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval);

	void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval, String group);

	/**
	 * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次,每隔repeatInterval秒执行一次
	 * 
	 * @param name
	 *            Quartz SimpleTrigger 名称
	 * @param startTime
	 *            调度开始时间
	 * @param endTime
	 *            调度结束时间
	 * @param repeatCount
	 *            重复执行次数
	 * @param repeatInterval
	 *            执行时间隔间
	 */
	void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval);

	void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval, String group);

	/**
	 * 暂停触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 */
	void pauseTrigger(String triggerName);

	/**
	 * 暂停触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 * @param group
	 *            触发器组
	 */
	void pauseTrigger(String triggerName, String group);

	/**
	 * 恢复触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 */
	void resumeTrigger(String triggerName);

	/**
	 * 恢复触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 * @param group
	 *            触发器组
	 */
	void resumeTrigger(String triggerName, String group);

	/**
	 * 删除触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 * @return
	 */
	boolean removeTrigdger(String triggerName);

	/**
	 * 删除触发器
	 * 
	 * @param triggerName
	 *            触发器名称
	 * @param group
	 *            触发器组
	 * @return
	 */
	boolean removeTrigdger(String triggerName, String group);
}

 

动态调度服务实现类:

package com.sundoctor.quartz.service;

import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

import org.quartz.CronExpression;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("schedulerService")
public class SchedulerServiceImpl implements SchedulerService {

	private static final String NULLSTRING = null;
	private static final Date NULLDATE = null;

	@Autowired
	private Scheduler scheduler;
	@Autowired
	private JobDetail jobDetail;

	@Override
	public void schedule(String cronExpression) {
		schedule(NULLSTRING, cronExpression);
	}

	@Override
	public void schedule(String name, String cronExpression) {
		schedule(name, NULLSTRING, cronExpression);
	}

	@Override
	public void schedule(String name, String group, String cronExpression) {
		try {
			schedule(name, group, new CronExpression(cronExpression));
		} catch (ParseException e) {
			throw new IllegalArgumentException(e);
		}
	}

	@Override
	public void schedule(CronExpression cronExpression) {
		schedule(NULLSTRING, cronExpression);
	}

	@Override
	public void schedule(String name, CronExpression cronExpression) {
		schedule(name, NULLSTRING, cronExpression);
	}

	@Override
	public void schedule(String name, String group, CronExpression cronExpression) {

		if (isValidExpression(cronExpression)) {

			if (name == null || name.trim().equals("")) {
				name = UUID.randomUUID().toString();
			}

			CronTriggerImpl trigger = new CronTriggerImpl();
			trigger.setCronExpression(cronExpression);

			TriggerKey triggerKey = new TriggerKey(name, group);

			trigger.setJobName(jobDetail.getKey().getName());
			trigger.setKey(triggerKey);

			try {
				scheduler.addJob(jobDetail, true);
				if (scheduler.checkExists(triggerKey)) {
					scheduler.rescheduleJob(triggerKey, trigger);
				} else {
					scheduler.scheduleJob(trigger);
				}
			} catch (SchedulerException e) {
				throw new IllegalArgumentException(e);
			}
		}
	}

	@Override
	public void schedule(Date startTime) {
		schedule(startTime, NULLDATE);
	}

	@Override
	public void schedule(Date startTime, String group) {
		schedule(startTime, NULLDATE, group);
	}

	@Override
	public void schedule(String name, Date startTime) {
		schedule(name, startTime, NULLDATE);
	}

	@Override
	public void schedule(String name, Date startTime, String group) {
		schedule(name, startTime, NULLDATE, group);
	}

	@Override
	public void schedule(Date startTime, Date endTime) {
		schedule(startTime, endTime, 0);
	}

	@Override
	public void schedule(Date startTime, Date endTime, String group) {
		schedule(startTime, endTime, 0, group);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime) {
		schedule(name, startTime, endTime, 0);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime, String group) {
		schedule(name, startTime, endTime, 0, group);
	}

	@Override
	public void schedule(Date startTime, int repeatCount) {
		schedule(null, startTime, NULLDATE, 0);
	}

	@Override
	public void schedule(Date startTime, Date endTime, int repeatCount) {
		schedule(null, startTime, endTime, 0);
	}

	@Override
	public void schedule(Date startTime, Date endTime, int repeatCount, String group) {
		schedule(null, startTime, endTime, 0, group);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime, int repeatCount) {
		schedule(name, startTime, endTime, 0, 0L);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime, int repeatCount, String group) {
		schedule(name, startTime, endTime, 0, 0L, group);
	}

	@Override
	public void schedule(Date startTime, int repeatCount, long repeatInterval) {
		schedule(null, startTime, NULLDATE, repeatCount, repeatInterval);
	}

	@Override
	public void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval) {
		schedule(null, startTime, endTime, repeatCount, repeatInterval);
	}

	@Override
	public void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval, String group) {
		schedule(null, startTime, endTime, repeatCount, repeatInterval, group);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval) {
		schedule(name, startTime, endTime, repeatCount, repeatInterval, NULLSTRING);
	}

	@Override
	public void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval, String group) {

		if (this.isValidExpression(startTime)) {

			if (name == null || name.trim().equals("")) {
				name = UUID.randomUUID().toString();
			}

			TriggerKey triggerKey = new TriggerKey(name, group);

			SimpleTriggerImpl trigger = new SimpleTriggerImpl();
			trigger.setKey(triggerKey);
			trigger.setJobName(jobDetail.getKey().getName());

			trigger.setStartTime(startTime);
			trigger.setEndTime(endTime);
			trigger.setRepeatCount(repeatCount);
			trigger.setRepeatInterval(repeatInterval);

			try {
				scheduler.addJob(jobDetail, true);
				if (scheduler.checkExists(triggerKey)) {
					scheduler.rescheduleJob(triggerKey, trigger);
				} else {
					scheduler.scheduleJob(trigger);
				}
			} catch (SchedulerException e) {
				throw new IllegalArgumentException(e);
			}
		}
	}

	@Override
	public void pauseTrigger(String triggerName) {
		pauseTrigger(triggerName, NULLSTRING);
	}

	@Override
	public void pauseTrigger(String triggerName, String group) {
		try {
			scheduler.pauseTrigger(new TriggerKey(triggerName, group));// 停止触发器
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void resumeTrigger(String triggerName) {
		resumeTrigger(triggerName, NULLSTRING);
	}

	@Override
	public void resumeTrigger(String triggerName, String group) {
		try {
			scheduler.resumeTrigger(new TriggerKey(triggerName, group));// 重启触发器
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean removeTrigdger(String triggerName) {
		return removeTrigdger(triggerName, NULLSTRING);
	}

	@Override
	public boolean removeTrigdger(String triggerName, String group) {
		TriggerKey triggerKey = new TriggerKey(triggerName, group);
		try {
			scheduler.pauseTrigger(triggerKey);// 停止触发器
			return scheduler.unscheduleJob(triggerKey);// 移除触发器
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}

	private boolean isValidExpression(final CronExpression cronExpression) {

		CronTriggerImpl trigger = new CronTriggerImpl();
		trigger.setCronExpression(cronExpression);

		Date date = trigger.computeFirstFireTime(null);

		return date != null && date.after(new Date());
	}

	private boolean isValidExpression(final Date startTime) {

		SimpleTriggerImpl trigger = new SimpleTriggerImpl();
		trigger.setStartTime(startTime);

		Date date = trigger.computeFirstFireTime(null);

		return date != null && date.after(new Date());
	}
}

 

SchedulerService 只有一个多态方法schedule,SchedulerServiceImpl实现SchedulerService接口,注入org.quartz.Schedulert和org.quartz.JobDetail,schedule方法可以动态配置org.quartz.CronExpression或org.quartz.SimpleTrigger调度时间。

五、实现自己的org.quartz.JobDetail

 

package com.sundoctor.example.service;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MyQuartzJobBean extends QuartzJobBean {

	private static final Logger logger = LoggerFactory.getLogger(MyQuartzJobBean.class);

	@Override
	protected void executeInternal(JobExecutionContext jobexecutioncontext) throws JobExecutionException {
		Trigger trigger = jobexecutioncontext.getTrigger();
		String triggerName = trigger.getKey().getName();

		SimpleService simpleService = getApplicationContext(jobexecutioncontext).getBean("simpleService",
				SimpleService.class);
		simpleService.testMethod(triggerName);

	}

	private ApplicationContext getApplicationContext(final JobExecutionContext jobexecutioncontext) {
		try {
			return (ApplicationContext) jobexecutioncontext.getScheduler().getContext().get("applicationContextKey");
		} catch (SchedulerException e) {
			logger.error("jobexecutioncontext.getScheduler().getContext() error!", e);
			throw new RuntimeException(e);
		}
	}

}

 

MyQuartzJobBean继承org.springframework.scheduling.quartz.QuartzJobBean,SimpleService如下:

package com.sundoctor.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service("simpleService")
public class SimpleService {

	private static final Logger logger = LoggerFactory.getLogger(SimpleService.class);

	public void testMethod(String triggerName) {
		// 这里执行定时调度业务
		logger.info(triggerName);
	}

}


SimpleService主要执行定时调度业务,在这里我只是简单打印一下log日志。
配置applicationContext-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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean name="quartzScheduler"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
		<property name="configLocation" value="classpath:quartz.properties" />
	</bean>

	<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass">
			<value>com.sundoctor.example.service.MyQuartzJobBean</value>
		</property>	
		<property name="durability" value="true" />	
	</bean>

</beans>

 
dataSource:项目中用到的数据源,里面包含了quartz用到的数据库表;
applicationContextSchedulerContextKey: 是org.springframework.scheduling.quartz.SchedulerFactoryBean这个类中把spring上下文以key/value的方式存放在了quartz的SchedulerContext,可以用applicationContextSchedulerContextKey所定义的key得到spring的ApplicationContext,然后就可使用ApplicationContext取得spring beans,使用方法参见MyQuartzJobBean;
configLocation:用于指明quartz的配置文件的位置,如果不用spring配置quartz的话,本身quartz是通过一个配置文件进行配置的,默认名称是quartz.properties,里面配置的参数在quartz的doc文档中都有介绍,可以调整quartz,我在项目中也用这个文件部分的配置了一些属性,代码如下:

org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

org.quartz.jobStore.misfireThreshold = 60000

#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.HSQLDBDelegate
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#org.quartz.jobStore.useProperties = true
org.quartz.jobStore.tablePrefix = QRTZ_ 
org.quartz.jobStore.isClustered = false 
org.quartz.jobStore.maxMisfiresToHandleAtATime=1 

 


这里面没有数据源相关的配置部分,采用spring注入datasource的方式已经进行了配置。

六、测试
运行如下测试类

package com.sundoctor.example.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sundoctor.quartz.service.SchedulerService;

public class MainTest {

	/**
	 * @param args
	 * @throws SchedulerException
	 */
	public static void main(String[] args) throws SchedulerException {

		ApplicationContext springContext = new ClassPathXmlApplicationContext(new String[] {
				"classpath:applicationContext.xml", "classpath:applicationContext-quartz.xml" });
		SchedulerService schedulerService = springContext.getBean("schedulerService", SchedulerService.class);

		// 执行业务逻辑...

		// 设置高度任务
		// 每10秒中执行调试一次
		schedulerService.schedule("0/10 * * ? * * *");

		Date startTime = parse("2014-08-19 16:33:00");
		Date endTime = parse("2014-08-22 21:10:00");

		// 2014-08-19 16:33:00开始执行调度
		schedulerService.schedule(startTime);

		// 2014-08-19 16:33:00开始执行调度,2014-08-22 21:10:00结束执行调试
		schedulerService.schedule(startTime, endTime);

		// 2014-08-19 16:33:00开始执行调度,执行5次结束
		schedulerService.schedule(startTime, 5);

		// 2014-08-19 16:33:00开始执行调度,每隔20秒执行一次,执行5次结束
		schedulerService.schedule(startTime, 5, 20);

		// 等等,查看com.sundoctor.quartz.service.SchedulerService

	}

	private static Date parse(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format.parse(dateStr);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

}

 
输出

[2014-08-19 22:31:50]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce
[2014-08-19 22:32:00]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce
[2014-08-19 22:32:10]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce
[2014-08-19 22:32:20]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce
[2014-08-19 22:32:30]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce
[2014-08-19 22:32:40]INFO  com.sundoctor.example.service.SimpleService(line:14) -7e132a81-6d24-44e1-8d6c-15cdaeefb2ce

 
这样只是简单的将quartz trigger名称打印出来。

这样通过SchedulerService就可以动态配置调度时间。其实SchedulerService 还可扩展,比如可以注入多个JobDetail,调度不同的JobDetail。

  • 大小: 56.6 KB
分享到:
评论
38 楼 bai_zzj 2011-09-27  
  找了很久,终于找到了!
37 楼 hahadeyouxi 2011-08-03  
你好,jobdetail的值和trigger的值不是JAR包自动插入进去的么?能否加我QQ1062079691,我想请教一下
36 楼 Angi 2010-05-28  
LL的蓝 写道
LZ你好 我刚看了你写的代码,自己也 写了一个,但我现在的项目有个需求,就是需要重复去调用定时任务
也就是说任务启动之后,就会处理一些业务,当这次业务处理完成后,隔2分钟后再次启动任务,就这样循环下去
但是这样就发现了问题,下一次任务启动的时候,系统的线程一直在增加,最后报内存溢出的错误

我是在SimpleService类的testMethod方法里调用
schedulerService.schedule("job01","job01",str01);
就出现以上情况
怎么样在循环下次的任务启动后,线程是不增加的,我试着加上删除job01的方法
scheduler.deleteJob("job01", Scheduler.DEFAULT_GROUP);
还是不管用,期待LZ的解答

同问,谢谢!
35 楼 LL的蓝 2010-05-17  
LZ你好 我刚看了你写的代码,自己也 写了一个,但我现在的项目有个需求,就是需要重复去调用定时任务
也就是说任务启动之后,就会处理一些业务,当这次业务处理完成后,隔2分钟后再次启动任务,就这样循环下去
但是这样就发现了问题,下一次任务启动的时候,系统的线程一直在增加,最后报内存溢出的错误

我是在SimpleService类的testMethod方法里调用
schedulerService.schedule("job01","job01",str01);
就出现以上情况
怎么样在循环下次的任务启动后,线程是不增加的,我试着加上删除job01的方法
scheduler.deleteJob("job01", Scheduler.DEFAULT_GROUP);
还是不管用,期待LZ的解答
34 楼 sundoctor 2010-03-29  
wjb_4595 写道
初学quartz

Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: Table 'slf.qrtz_locks' doesn't exist [See nested exception: java.sql.SQLException: Table 'slf.qrtz_locks' doesn't exist]]

没有default-autowire="byName"属性; autowire="no" org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore还是报错


错误很明显,表slf.qrtz_locks不存在,改为org.quartz.impl.RAMJobStore还是报错,可以你在什么地方的配置没有改对
33 楼 wjb_4595 2010-03-29  
初学quartz

Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: Table 'slf.qrtz_locks' doesn't exist [See nested exception: java.sql.SQLException: Table 'slf.qrtz_locks' doesn't exist]]

没有default-autowire="byName"属性; autowire="no" org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore还是报错
32 楼 aisini_an 2010-02-08  
前几天还在搞这个,看完LZ帖子,又学到不少的新知识。好好收藏.
31 楼 renco 2010-02-05  
最近项目里面正需要集成quartz 感谢兰州
30 楼 马伽角 2010-02-01  
谢谢你,,,,换成Oracle就好了
29 楼 sundoctor 2010-01-29  
不能获得当前配置的数据连接,应该是你的数据库某方面出问题,好好检查一下数据库配置
28 楼 马伽角 2010-01-22  
你好楼主。。。。这是我运行你的例子报的错。麻烦你参考参考,,帮我解决解决
这是报错的代码:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzScheduler' defined in file [E:\Tomcat 5.5\webapps\Q\WEB-INF\classes\spring\applicationContext-quartz.xml]: Invocation of init method failed; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
	at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3795)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4252)
	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
	at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
	at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
	at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
	at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
	at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
	at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
	at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
	at org.apache.catalina.core.StandardService.start(StandardService.java:448)
	at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
	at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:585)
	at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]]
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.initialize(JobStoreSupport.java:606)
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.initialize(JobStoreCMT.java:144)
	at org.springframework.scheduling.quartz.LocalDataSourceJobStore.initialize(LocalDataSourceJobStore.java:133)
	at org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1225)
	at org.quartz.impl.StdSchedulerFactory.getScheduler(StdSchedulerFactory.java:1376)
	at org.springframework.scheduling.quartz.SchedulerFactoryBean.createScheduler(SchedulerFactoryBean.java:575)
	at org.springframework.scheduling.quartz.SchedulerFactoryBean.afterPropertiesSet(SchedulerFactoryBean.java:451)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
	... 39 more
Caused by: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.getNonManagedTXConnection(JobStoreCMT.java:167)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3750)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3722)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.cleanVolatileTriggerAndJobs(JobStoreSupport.java:746)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.initialize(JobStoreSupport.java:604)
	... 47 more
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:264)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at com.mchange.v2.c3p0.ComboPooledDataSource.getConnection(ComboPooledDataSource.java:521)
	at org.springframework.scheduling.quartz.LocalDataSourceJobStore$2.getConnection(LocalDataSourceJobStore.java:125)
	at org.quartz.utils.DBConnectionManager.getConnection(DBConnectionManager.java:112)
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.getNonManagedTXConnection(JobStoreCMT.java:164)
	... 51 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:972)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:260)
	... 56 more
[2010-01-22 11:44:09]ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/Q](line:3799) -Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzScheduler' defined in file [E:\Tomcat 5.5\webapps\Q\WEB-INF\classes\spring\applicationContext-quartz.xml]: Invocation of init method failed; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
	at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3795)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4252)
	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
	at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
	at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
	at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
	at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
	at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
	at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
	at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
	at org.apache.catalina.core.StandardService.start(StandardService.java:448)
	at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
	at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:585)
	at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]]
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.initialize(JobStoreSupport.java:606)
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.initialize(JobStoreCMT.java:144)
	at org.springframework.scheduling.quartz.LocalDataSourceJobStore.initialize(LocalDataSourceJobStore.java:133)
	at org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1225)
	at org.quartz.impl.StdSchedulerFactory.getScheduler(StdSchedulerFactory.java:1376)
	at org.springframework.scheduling.quartz.SchedulerFactoryBean.createScheduler(SchedulerFactoryBean.java:575)
	at org.springframework.scheduling.quartz.SchedulerFactoryBean.afterPropertiesSet(SchedulerFactoryBean.java:451)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
	... 39 more
Caused by: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'springNonTxDataSource.quartzScheduler': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.getNonManagedTXConnection(JobStoreCMT.java:167)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3750)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3722)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.cleanVolatileTriggerAndJobs(JobStoreSupport.java:746)
	at org.quartz.impl.jdbcjobstore.JobStoreSupport.initialize(JobStoreSupport.java:604)
	... 47 more
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:264)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at com.mchange.v2.c3p0.ComboPooledDataSource.getConnection(ComboPooledDataSource.java:521)
	at org.springframework.scheduling.quartz.LocalDataSourceJobStore$2.getConnection(LocalDataSourceJobStore.java:125)
	at org.quartz.utils.DBConnectionManager.getConnection(DBConnectionManager.java:112)
	at org.quartz.impl.jdbcjobstore.JobStoreCMT.getNonManagedTXConnection(JobStoreCMT.java:164)
	... 51 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:972)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:260)
	... 56 more
27 楼 rickyboy 2010-01-14  
sundoctor 写道
ApplicationContext springContext = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:applicationContext-quartz.xml"});
SchedulerService schedulerService = (SchedulerService)springContext.getBean("schedulerService");
		
//执行业务逻辑...
		
//设置高度任务
//每10秒中执行调试一次
schedulerService.schedule("0 * * ? * * *"); 
...


数据库中有多条cronExpression,每条cronExpressionf都会执行,这是肯定的。

这里只是测试,只是说明SchedulerService接口的使用方法...........................................


明白了~谢谢!
我看了一下spring里面的源码~和里面的大致吻合,不过我对quartz非常陌生。
你的文章让我理解的更深了。
26 楼 sundoctor 2010-01-14  
ApplicationContext springContext = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:applicationContext-quartz.xml"});
SchedulerService schedulerService = (SchedulerService)springContext.getBean("schedulerService");
		
//执行业务逻辑...
		
//设置高度任务
//每10秒中执行调试一次
schedulerService.schedule("0 * * ? * * *"); 
...


数据库中有多条cronExpression,每条cronExpressionf都会执行,这是肯定的。

这里只是测试,只是说明SchedulerService接口的使用方法...........................................
25 楼 rickyboy 2010-01-13  
我运行一次测试
就往数据库cron Trigger表中插入一条记录
那我每次运行的话
数据库中有多条cronExpression会不会同时执行啊

有点不解
24 楼 diddyrock 2010-01-12  
多谢!狠有用
23 楼 yf42 2009-09-25  
cronExpression直接用el表达式呗,想设啥值设啥值
22 楼 lixiaoyuf709 2009-09-24  
顶一个,前些日子做项目用的是静态的,想看看动态的这么搞,一直还找不到,谢
21 楼 sundoctor 2009-09-15  
补充:增加hibernate

经过这段时间,有人在本例子上增加hibernate后遇到好些问题
请参考另一贴《Quartz任务监控管理》,http://www.iteye.com/topic/441951?page=3,对于hibenate的问题,我在那做了总结
20 楼 sundoctor 2009-09-13  
yanyu510 写道
yanyu510 写道
我还想问一下,我做的数据库备份操作话在testMethod里面,服务器启动的时候时间没到也会调用一次,这样不就乱了吗?这个问题怎么解决?

还有就是我把bakcupDao注入到simpleSerivce里了,我的backupDao里是这么写的:
public boolean backupDateabase(String dbname, String bfname) {
		final String dbName = dbname;
		final String bfname1 = bfname;
		return (Boolean) super.getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session) {
						boolean flag = true;
						PreparedStatement pstmt = null;

						try {
							pstmt = session.connection().prepareStatement(
									"{call p_Backup_Or_Restore(?,?,?)}");
							pstmt.setString(1, bfname1);
							pstmt.setString(2, dbName);
							pstmt.setInt(3, 1);
							pstmt.execute();
							System.out.println("数据库已备份");
						} catch (Exception e) {
							flag = false;
							e.printStackTrace();
						}
						return flag;
					}
				});
	}

执行这个方法的,super.getHibernateTemplate()得到的hibernateTemplate为空,是什么原因?
我是初学者,有很多问题不懂,还请LZ多多指导,谢啦!



服务器起来时不会调用一次的,调不调用跟你的配置时间有关系,时间不到绝不会自动调用的,这个你放心好了

上面说过simpleService和其中注入各属性需要实现Serializable序列化接口,你的BakcupDao继承自HibernateDaoSupport虽然也实现了序列化接口,但是HibernateDaoSupport里的HibernateTemplate并没有实现序列化接口,所以你取得的HibernateTemplate永远为null。因此获取HibernateTemplate必须换一种方式,你的BakcupDao不能继承自HibernateDaoSupport。HibernateTemplate没有实现序列化接口,而SessionFactory是实现序列化接口的,在bakcupDao注入SessionFactory,通过SessionFactory获取HibernateTemplate。

你的bakcupDao可以这样写

import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sundoctor.example.service.SimpleService;

@Repository("bakcupDao")
public class BakcupDao implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;	
	private SessionFactory sessionFactory;	

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;		
	}


	public boolean backupDateabase(String dbname, String bfname) {
		final String dbName = dbname;
		final String bfname1 = bfname;
            HibernateTemplate  hibernateTemplate = new HibernateTemplate(sessionFactory);
		return (Boolean)hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				boolean flag = true;
				PreparedStatement pstmt = null;

				try {
					pstmt = session.connection().prepareStatement("{call p_Backup_Or_Restore(?,?,?)}");
					pstmt.setString(1, bfname1);
					pstmt.setString(2, dbName);
					pstmt.setInt(3, 1);
					pstmt.execute();
					System.out.println("数据库已备份");
				} catch (Exception e) {
					flag = false;
					e.printStackTrace();
				}
				return flag;
			}
		});
	}
}	


19 楼 yanyu510 2009-09-12  
yanyu510 写道
我还想问一下,我做的数据库备份操作话在testMethod里面,服务器启动的时候时间没到也会调用一次,这样不就乱了吗?这个问题怎么解决?

还有就是我把bakcupDao注入到simpleSerivce里了,我的backupDao里是这么写的:
public boolean backupDateabase(String dbname, String bfname) {
		final String dbName = dbname;
		final String bfname1 = bfname;
		return (Boolean) super.getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session) {
						boolean flag = true;
						PreparedStatement pstmt = null;

						try {
							pstmt = session.connection().prepareStatement(
									"{call p_Backup_Or_Restore(?,?,?)}");
							pstmt.setString(1, bfname1);
							pstmt.setString(2, dbName);
							pstmt.setInt(3, 1);
							pstmt.execute();
							System.out.println("数据库已备份");
						} catch (Exception e) {
							flag = false;
							e.printStackTrace();
						}
						return flag;
					}
				});
	}

执行这个方法的,super.getHibernateTemplate()得到的hibernateTemplate为空,是什么原因?
我是初学者,有很多问题不懂,还请LZ多多指导,谢啦!

相关推荐

    Spring Quartz如何动态配置时间

    在本文中,我们将讨论如何使用 Spring Quartz 实现动态配置时间,并提供了详细的实现步骤和实践经验。 动态配置时间的目的 在实际应用中,任务的执行时间往往需要根据业务需求进行动态调整,以满足不同的需求场景...

    quartz整合springbatch动态集群定时实现mysql参考

    在这个“quartz_springbatch_dynamic”项目中,我们将看到如何将这两个强大的工具结合起来,以实现动态集群环境中的定时任务执行,并使用MySQL作为数据存储。 Quartz是一个开源的作业调度框架,允许开发者创建、...

    Quartz在Spring中动态设置cronExpression

    标题与描述均聚焦于“Quartz在Spring中动态设置cronExpression”的主题,这涉及到了两个主要的开源项目:Quartz,一个强大的作业调度框架;以及Spring,一个广泛使用的Java平台框架,用于构建企业级应用程序。Quartz...

    quartz在Spring中的配置

    通过上述配置,不仅可以在 Spring 应用中实现定时任务的管理,还能根据实际需求动态调整任务的执行时间和状态。这种方式特别适用于需要频繁变更调度规则的应用场景,如 Web 应用中的报表生成、数据同步等任务。使用...

    Spring中的Quartz配置-Spring-定时器-java定时器.doc

    在本篇文章中,我们将讨论如何在 Spring 中配置 Quartz,以实现 Java 定时器的功能。 Quartz 介绍 Quartz 是一个开源的作业调度器,可以让开发者轻松地实现任务的定时执行。它提供了强大的调度功能,可以满足复杂...

    定时器的配置文件(两种方式:springmvc自带定时,Quartz与spring结合的定时)

    在Spring配置文件(如`applicationContext.xml`)中配置Quartz的SchedulerFactoryBean。 ```xml &lt;bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt; ...

    关于spring中quartz的配置

    在Spring配置文件(如`applicationContext.xml`)中,定义`SchedulerFactoryBean`来实例化和配置Quartz Scheduler: ```xml &lt;bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz....

    Spring Quartz动态配置时间.rar

    这个压缩包“Spring Quartz动态配置时间.rar”包含的PDF文档很可能是关于如何在Spring框架中使用Quartz进行动态配置时间的详细教程。下面将详细介绍Spring集成Quartz进行动态任务调度的相关知识点。 1. **Quartz...

    spring mvc quartz 动态设置时间

    - 在`web.xml`中,通过`contextConfigLocation`参数指定了Spring配置文件的位置,这样Spring会自动加载`applicationContext-quartz.xml`。 3. **业务逻辑**: - `SysScheduleServiceImpl`类实现了`...

    spring整合java quartz实现动态定时任务的前台网页配置与管理

    在实际项目应用中经常会用到定时任务,可以通过quartz和spring的简单配置即可完成,但如果要改变任务的执行时间、频率,废弃任务等就需要改变配置甚至代码需要重启服务器,这里介绍一下如何通过quartz与spring的组合...

    quartz和spring-quartz

    学习Quartz和Spring-Quartz,不仅需要理解它们的基本概念,还要掌握如何在实际项目中进行配置和使用。例如,创建一个定时任务,你需要定义Job类,配置Trigger,然后在Spring的配置文件中设置Scheduler。此外,熟悉...

    Spring中Quartz的配置

    接下来是在Spring配置文件中对Quartz进行配置。以下是配置示例: ```xml &lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt; &lt;!-- 要调用的工作类 --&gt; ...

    spring quartz 非配置动态定时

    在Spring配置文件中,可以使用`SchedulerFactoryBean`来初始化并管理Scheduler。这个bean将负责启动、停止Scheduler,以及处理其他相关的生命周期事件。 在非配置动态定时任务中,我们不再在XML或Java配置中硬编码...

    Spring整合quartz2.2.3总结,quartz动态定时任务,Quartz定时任务集群配置

    2. 配置Scheduler:在Spring的配置文件中,使用`SchedulerFactoryBean`来初始化和配置Quartz Scheduler。可以设置如数据库存储、线程池大小等参数。 3. 创建Job类:定义一个实现了`org.quartz.Job`接口的类,这是...

    定时器(quartz+spring)读取数据库配置

    最后,启动Spring容器,Quartz会自动加载数据库中的Job和Trigger配置,按照设定的时间执行相应的任务。 通过这种方式,我们可以构建一个高度可扩展和可配置的定时任务系统,只需在数据库中修改Job和Trigger的配置,...

    Quartz+Spring定时触发器例子

    - 如何在Spring中配置Quartz - 如何创建和配置JobDetail和Trigger - Cron表达式的使用和理解 - 如何在Job类中注入依赖 - 如何启动和停止Scheduler - 如何调试和管理定时任务 总的来说,"Quartz+Spring定时触发器...

    SSH+quartz实现的可动态配置时间规则的定时任务

    在这个项目中,Hibernate可能被用来存储和检索quartz的作业和触发器信息,包括时间规则,这样就可以在数据库中动态更新任务配置,而无需修改代码。 4. **Quartz库**:Quartz是Java中广泛使用的任务调度库,它可以...

Global site tag (gtag.js) - Google Analytics