使用spring quartz 进行持久化的任务调度

时间:2022-05-13 19:59:41

从quartz的发布包中找到docs/dbTables/目录下的sql脚本,创建数据库表。

applicationContext.xml的配置

<bean id="schedulerFactory"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>

package com.wxl.app.quartz;

import java.util.Map;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

public class PersistentJob implements StatefulJob {
public PersistentJob() {
System.out.println("PersistentJob");
}

public void execute(JobExecutionContext jc) throws JobExecutionException {
Map map = jc.getJobDetail().getJobDataMap();
System.out.println("[" + jc.getJobDetail().getName() + "]"
+ map.get("message"));
}

}

package com.wxl.app.quartz;

import java.util.Calendar;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringWithJobPersistence {
public static void main(String[] args) throws SchedulerException {
ApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Scheduler scheduler = (Scheduler) ac.getBean("schedulerFactory");
JobDetail jobDetail = new JobDetail("job1", PersistentJob.class);
JobDetail jobDetail2 = new JobDetail("job2", PersistentJob.class);
jobDetail.getJobDataMap().put("message", "aaa");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
scheduler.scheduleJob(jobDetail, new SimpleTrigger("simpleTrigger1",
Scheduler.DEFAULT_GROUP, cal.getTime(), null, 0, 15000));

jobDetail2.getJobDataMap().put("message", "bbb");
scheduler.scheduleJob(jobDetail2, new SimpleTrigger("simpleTrigger2",
Scheduler.DEFAULT_GROUP, cal.getTime(), null, 0, 15000));
}
}