Quartz Calendars can be used by the scheduler to block of a list of days, range of time or particular days of the year/month/week from the scheduler fire timings. Attaching a calendar onto a trigger ensures that the trigger does not get fired on date/time as defined by the Calendar.
There are different types of Calendar already available or a new Calendar can be using the Quartz calendar interface. List of available calendars on quartz can be got here
The below sample shows the use of one such Calendar – WeeklyCalendar that disables job fire on weekends – perfect for our AlarmScheduler application. The method of using it is to first create an object of the WeeklyCalendar and then add it onto the scheduler along with a string name through which it can be further referenced. Then, this string name is used as an argument in setting the calendar name for the trigger.
import java.util.Calendar; import java.util.Date; import java.util.Properties; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.calendar.WeeklyCalendar; import static org.quartz.CronScheduleBuilder.dailyAtHourAndMinute; import static org.quartz.JobBuilder.newJob; public class AlarmSchedule { public AlarmSchedule(){ try{ //Create the weekly calendar object - This by default handles disaabling job fire on weekends so no need //to explicitly set WeeklyCalendar weeklyOff = new WeeklyCalendar(); //example of adding an excluded day of the week - This excludes fridays from job firing schedule //weeklyOff.setDayExcluded(Calendar.FRIDAY, true); SchedulerFactory schdFact = new StdSchedulerFactory(); Scheduler schd = schdFact.getScheduler(); //add the Calendar object created to the scheduler with a string identifier to it schd.addCalendar("weeklyOff", weeklyOff, false, true); schd.start(); JobDetail job = newJob(AlarmJob.class).withIdentity("alarmjob", "alarmjobgroup").build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("alarmtrigger", "alarmtriggergroup") .startNow() .withSchedule(dailyAtHourAndMinute(6, 30)) .modifiedByCalendar("weeklyOff") .build(); schd.scheduleJob(job,trigger); } catch(SchedulerException e){ e.printStackTrace(); } } public static void main(String[] args) { new AlarmSchedule(); } }
AlarmJob.java –
import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class AlarmJob implements Job { @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("WAKE UP CALL "+new Date()); } }
Code @ Git – https://github.com/vageeshhoskere/blog
Nice post! Would like to seek your help if you any idea about this requirement – can I update a quartz calendar object after the scheduler is deployed? What i mean is, say i am using a holiday calendar, i should be able to change the calendar information and quartz will automatically use the updated calendar..