`
sundoctor
  • 浏览: 325741 次
  • 性别: 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
分享到:
评论
58 楼 ly8951677 2017-08-03  
可以运行了。不过怎么进行多任务添加呢?
57 楼 chenqu 2017-06-21  
Lz
你好,
我点击maven的install按钮,出现以下错误:
/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=/Users/a15000209592/Desktop/develop/quartzWithSpring "-Dmaven.home=/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3" "-Dclassworlds.conf=/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/bin/m2.conf" -Didea.launcher.port=7535 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds-2.5.2.jar:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=2016.3 -s /Users/a15000209592/.m2/settings.xml -Dmaven.repo.local=/Users/a15000209592/.m2/repository install
[INFO] Scanning for projects...
[INFO]                                                                        
[INFO] ------------------------------------------------------------------------
[INFO] Building quartzWithSpring 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ quartzWithSpring ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 27 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ quartzWithSpring ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 4 source files to /Users/a15000209592/Desktop/develop/quartzWithSpring/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ quartzWithSpring ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ quartzWithSpring ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 2 source files to /Users/a15000209592/Desktop/develop/quartzWithSpring/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ quartzWithSpring ---
[INFO] Surefire report directory: /Users/a15000209592/Desktop/develop/quartzWithSpring/target/surefire-reports

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.sundoctor.example.test.SimpleServiceTest
[2017-06-21 18:29:48]ERROR org.springframework.test.context.TestContextManager(line:231) -Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@49c7b90e] to prepare test instance [com.sundoctor.example.test.SimpleServiceTest@10d307f1]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sundoctor.example.test.SimpleServiceTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sundoctor.quartz.service.SchedulerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sundoctor.quartz.service.SchedulerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:508)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:486)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
... 32 more
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 24.989 sec <<< FAILURE!
test(com.sundoctor.example.test.SimpleServiceTest)  Time elapsed: 0.003 sec  <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sundoctor.example.test.SimpleServiceTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sundoctor.quartz.service.SchedulerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sundoctor.quartz.service.SchedulerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:508)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:486)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
... 32 more


Results :

Tests in error:
  test(com.sundoctor.example.test.SimpleServiceTest): Error creating bean with name 'com.sundoctor.example.test.SimpleServiceTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sundoctor.quartz.service.SchedulerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 27.914 s
[INFO] Finished at: 2017-06-21T18:29:48+08:00
[INFO] Final Memory: 17M/172M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project quartzWithSpring: There are test failures.
[ERROR]
[ERROR] Please refer to /Users/a15000209592/Desktop/develop/quartzWithSpring/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Process finished with exit code 1


求帮忙解答,谢谢
56 楼 cwjattop 2016-08-10  
Many thanks to your sharing.
55 楼 刺客8882010 2015-08-07  
SimpleTriggerImpl、CronTriggerImpl是一个类还是一个接口?麻烦问下写的是不是不完整呢?
53 楼 zqb666kkk 2015-04-21  
jdbc.url=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true

这个数据库有吗
52 楼 烈冬冰夏 2015-02-26  
学习了。
51 楼 lxcaoxin 2014-11-26  
文件损坏了吧,下载后解压没有东西。另外想问一下,能实现数据库的时间配置改变了,定时任务会识别到吗?
50 楼 qkjava 2014-11-11  
多年之后 把这帖子翻出来 重新温习一下,项目中有用到。
49 楼 xielanjun910728 2014-06-25  
很给力,很赞!
48 楼 Jackie_GP 2013-12-31  
那里有创建表的脚步呢?
47 楼 guan2468 2013-12-05  
按照群主你的Quartz任务监控管理 的配值,如何让任务变成有状态的任务,不能并发,就是加上<property name="concurrent" value="false" />



我已经可以动态加载,但是任务还是并发,把这句代码放在那里,可以让他不并发。



底下是我要完成的要求

在quartz和sping整合中动态执行加载的定时任务,定时任务是有状态的,不能并发。
46 楼 guan2468 2013-12-05  
按照群主你的Quartz任务监控管理 的配值,如何让任务变成有状态的任务,不能并发,就是加上<property name="concurrent" value="false" />



我已经可以动态加载,但是任务还是并发,把这句代码放在那里,可以让他不并发。



底下是我要完成的要求

在quartz和sping整合中动态执行加载的定时任务,定时任务是有状态的,不能并发。
45 楼 osacar 2013-05-15  
十二张表都是跟这个动态调度有关?也就说要十二表才能实现这个功能么?
还没看源码
44 楼 old 2012-08-01  
没有表结构呀,怎么用
43 楼 adyuebanwan 2012-06-14  
这么多年了,不知道楼主还记得不记得这篇文章了
quartz有两种方式:RAMJobStore和JdbcJobStore两种
遇到个问题,跑了下楼主的QuartzWithSpring项目,发现不管我怎么修改,
都会采用持久数据的方式,RAMJobStore无法使用,好纠结啊。试了很多种方法都不行

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

我来回答自己的问题吧:
折腾了好几天,进入quartz源码调试一番才知道,是下面这个东西在搞鬼
org.quartz.scheduler.instanceName = StoreQuartzScheduler_1
这个名字要不能重复,而且自由定义,工程中spring已经加载了class name 为DefaultQuartzScheduler的实例,所以我配置的没用了,就一直默认采用RAM方式
quartz版本1.6.6
StdSchedulerFactory 的1377行代码

    public Scheduler getScheduler() throws SchedulerException {
        if (cfg == null) {
            initialize();
        }

        SchedulerRepository schedRep = SchedulerRepository.getInstance();

        Scheduler sched = schedRep.lookup(getSchedulerName());

        if (sched != null) {
            if (sched.isShutdown()) {
                schedRep.remove(getSchedulerName());
            } else {
                return sched;//这里居然给我自动返回了
            }
        }

        sched = instantiate();//改了之后才执行这段代码

        return sched;
    }

对spring的单例注入方式真是 哎,希望对遇到同样问题的人有用
42 楼 adyuebanwan 2012-06-13  
这么多年了,不知道楼主还记得不记得这篇文章了
quartz有两种方式:RAMJobStore和JdbcJobStore两种
遇到个问题,跑了下楼主的QuartzWithSpring项目,发现不管我怎么修改,
都会采用持久数据的方式,RAMJobStore无法使用,好纠结啊。试了很多种方法都不行

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

请教啊
41 楼 天之南极 2012-04-20  
好好学习下楼主发的帖子
40 楼 txin0814 2011-12-21  
mark.
39 楼 spring0827 2011-10-26  
你好,看了你挺详细,还有些细节的问题 我不太明白,请您加下我QQ:664182695

相关推荐

    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`类实现了`...

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

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

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

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

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

Global site tag (gtag.js) - Google Analytics