package com.cavaness.quartzbook.chapter3;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
/**
* 创建调度器,并调度作业
* @author Kevin
*
*/
public class Listing_3_5 {
private static Log log = LogFactory.getLog(Listing_3_5.class);
/**
* 创建调度器
* @throws SchedulerException
*/
public Scheduler createScheduler() throws SchedulerException {
try {
return StdSchedulerFactory.getDefaultScheduler();
} catch (SchedulerException e) {
log.error("创建调度器失败!", e);
throw e;
}
}
/**
* 把Job注册到Scheduler,所以先定义一个 JobDetail,并关联到这个 Scheduler实例
* @throws SchedulerException
*/
public void scheduleJob(Scheduler scheduler) throws SchedulerException {
JobDetail scanDirectoryJobDetail = new JobDetail("ScanDirectoryJob",
Scheduler.DEFAULT_GROUP, ScanDirectoryJob.class);// 为作业取名字,分组
scanDirectoryJobDetail.getJobDataMap().put("SCAN_DIRECTORY",
"G:\\JavaEE\\Data\\Web Services"); // 配置作业
Trigger scanDirectoryJobTrigger = TriggerUtils.makeSecondlyTrigger(10); // 创建触发器,每10秒触发一次
scanDirectoryJobTrigger.setName("scanDirectoryJobTrigger"); // 为触发器取名
scanDirectoryJobTrigger.setStartTime(new Date()); // 即时启动触发器
try {
scheduler.scheduleJob(scanDirectoryJobDetail, scanDirectoryJobTrigger); // 关联JobDetail和触发器
} catch (SchedulerException e) {
log.error("关联JobDetail和触发器失败!", e);
throw e;
}
}
public static void main(String[] args) throws SchedulerException {
Listing_3_5 listing_3_5 = new Listing_3_5();
Scheduler scheduler = null;
try {
scheduler = listing_3_5.createScheduler(); // 创建调度器
} catch (SchedulerException e) {
log.error("创建调度器失败!", e);
throw e;
}
listing_3_5.scheduleJob(scheduler); // 把Job注册到Scheduler,所以先定义一个 JobDetail,并关联到这个 Scheduler实例
scheduler.start();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
log.info("调度器启动时间:" + simpleDateFormat.format(new Date()));
}
}