一 配置xml如下:
<!-- 定时任务配置 -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="true">
<!-- <property name="triggers">
<list>
<ref bean="t1" />
</list>
</property> -->
</bean>
<!-- 配置作业类JobDetailBean -->
<bean id="job1" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="test.Job1"></property>
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="0"></entry>
</map>
</property>
</bean> <!-- 配置作业调度的触发方式(触发器) -->
<!-- 第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。 -->
<!-- <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="job1" />
<property name="cronExpression" value="0 0 12 * * ?" />
</bean> --> <!-- 第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job1" />
<property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->
<property name="repeatInterval" value="2000" /><!-- 每2秒调度一次 -->
</bean>
二 手动获取scheduler调度对象,触发SimpleTriggerBean对象,和作业类JobDetailBean对象
public class TestJob {
public static QuarzJobHelper jobHelper;
/**任务调度对象*/
private static Scheduler scheduler;
static AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");
static{
jobHelper = (QuarzJobHelper)context.getBean("jobHelper");
/**任务调度对象*/
scheduler = (Scheduler)context.getBean("scheduler");
}
public static void main(String[] args) {
//从spring中获取trigger
Trigger trigger = (Trigger)context.getBean("cronTrigger");
//获取job作业类
JobDetail detail = (JobDetail)context.getBean("job1");
try {
//新增job
scheduler.scheduleJob(detail, trigger);
System.out.println(detail.getName()+","+detail.getGroup());
Thread.sleep(9000);
//删除job
scheduler.deleteJob(detail.getName(), detail.getGroup());
//定时任务销毁
scheduler.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
} }