package com.cavaness.quartzbook.chapter3;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.AnnualCalendar;
import org.quartz.impl.calendar.WeeklyCalendar;
/**
* 编程式调度器,排除每周的某一天
* @author Kevin
*
*/
public class Listing_4_9 {
private static Log log = LogFactory.getLog(Listing_3_5.class);
/**
* 创建,启动调度器
* @throws SchedulerException
*/
public void startScheduler() throws SchedulerException {
Scheduler scheduler = null;
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
} catch (SchedulerException e) {
log.error("调度器创建失败!", e);
throw e;
}
try {
scheduler.start();
} catch (SchedulerException e) {
log.error("调度器启动失败!", e);
throw e;
}
log.info("调度器启动时间:" + new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()));
scheduleJob(scheduler, PrintInfoJob.class);
}
/**
* 配置作业,创建触发器
* @param scheduler 调度器
* @param jobClass 作业所在的类
* @throws SchedulerException
*/
public void scheduleJob(Scheduler scheduler, Class jobClass) throws SchedulerException {
WeeklyCalendar weeklyCalendar = new WeeklyCalendar(); // 排除每个星期的周一,但由于默认的缘故,SATURDAY and SUNDAY也会被排除 ,
weeklyCalendar.setDayExcluded(Calendar.MONDAY, true); // 此种方法排除了三天,并不能真正做到只排除一天
try {
scheduler.addCalendar("bankHolidays", weeklyCalendar, true, true); // 两个true分别表示替换和更新原来的WeeklyCalendar
} catch (SchedulerException e) {
log.error("为调度器关联annualCalendar失败!", e);
throw e;
}
Trigger printInfoTrigger = TriggerUtils.makeImmediateTrigger("printInfoTrigger",
SimpleTrigger.REPEAT_INDEFINITELY, 10000);
printInfoTrigger.setCalendarName("bankHolidays"); // 关联触发器和calendar
JobDetail printInfoJobDetail = new JobDetail("printInfoJobDetail", Scheduler.DEFAULT_GROUP, jobClass);
try {
scheduler.scheduleJob(printInfoJobDetail, printInfoTrigger); // 关联触发器和调度器
} catch (SchedulerException e) {
log.error("关联触发器printInfoTrigger和调度器scheduler失败!", e);
throw e;
}
}
public static void main(String[] args) throws SchedulerException {
Listing_4_9 listing_4_9 = new Listing_4_9();
listing_4_9.startScheduler();
}
}
排除每周的某一天
最新推荐文章于 2024-08-12 13:50:50 发布