I had slightly different requirements. However, I thought I'd leave this here for future readers.
Basically you can set advanced scheduling with a CronTrigger which takes a CronExpression.
Lesson 6: CronTrigger
CronTriggers are often more useful than SimpleTrigger, if you need a
job-firing schedule that recurs based on calendar-like notions, rather
than on the exactly specified intervals of SimpleTrigger.
With CronTrigger, you can specify firing-schedules such as “every
Friday at noon”, or “every weekday and 9:30 am”, or even “every 5
minutes between 9:00 am and 10:00 am on every Monday, Wednesday and
Friday”.
Even so, like SimpleTrigger, CronTrigger has a startTime which
specifies when the schedule is in force, and an (optional) endTime
that specifies when the schedule should be discontinued.
Cron Expressions
Cron-Expressions are used to configure instances of CronTrigger.
Cron-Expressions are strings that are actually made up of seven
sub-expressions, that describe individual details of the schedule.
These sub-expression are separated with white-space, and represent:
- Seconds
- Minutes
- Hours
- Day-of-Month
- Month
- Day-of-Week
- Year (optional field)
An example of a complete cron-expression is the string
“0 0 12 ? * WED” - which means “every Wednesday at 12:00 pm”.
Example Implementation
There are many ways to set and scaffold Quartz.Net, and the code I use may vary a lot to other implementations, however someone might find this useful.
public static void SetSchedule<T>(this IScheduler source, TimeSpan minWaitSeconds, string cron)
where T : IJob
{
var jobName = typeof(T).Name;
var triggerKey = new TriggerKey($"{jobName} Trigger");
DateTimeOffset minNextTime = DateTime.UtcNow.AddSeconds(2) + minWaitSeconds;
var trigger = TriggerBuilder.Create()
.WithIdentity(triggerKey)
.StartAt(minNextTime)
.WithCronSchedule(cron)
.Build();
var jobKey = new JobKey(jobName);
var job = JobBuilder.Create<T>()
.WithIdentity(jobKey)
.Build();
source.ScheduleJob(job, trigger);
}
Usage
var startAt = new TimeSpan(0, 0, 0, 5);
var schedule = "0/5 * 8-16 ? * MON-FRI"
scheduler.SetSchedule<WarehousePickupNotificationJob>(startAt, schedule);
Note : My use case was that I needed a Task to run every 5 seconds, between certain hours, on week days.
Breakdown
"0/5 * 8-17 ? * MON-FRI"
0/5
- Seconds (The
/
character can be used to specify increments to values), which reads as run every 5 seconds
*
- Minutes (
*
denotes all), which reads all minutes
8-16
- Hours (
-
denotes to), which reads from "8am to 5pm" Not that the end number is inclusive
?
- Day-of-Month (The
?
character is allowed for the day-of-month and day-of-week fields. It is used to specify "no specific value")
*
- Month field (
*
denotes all), which reads all months
MON-FRI
- Day-of-Week (
-
denotes to), which reads all week days