Scheduling
Scheduling allows to create and configure to run jobs at specific times. It can be simple one e.g. running a job every few seconds or more complex e.g. every minute, between 8am and 5pm, every day.
How to create a scheduled service
In order to create a scheduled job it's necessary to implement IScheduledJob interface and then register it.
public class MyScheduledJob : IScheduledJob
{
public async Task RunAsync()
{
// Perform your scheduled job here
}
}
await ArconQApp.StartAsync(args, services =>
{
services.AddScheduledJob<MyScheduledJob>().WithIntervalSchedule(7, IntervalType.Seconds);
});
This setup will execute MyScheduledJob every 7 seconds
Registration types
There are two ways of defining frequency of a scheduled job.
.WithIntervalSchedule - Defining frequency in a convenient way
//Executes every 10 seconds
services.AddScheduledJob<MyScheduledJob>().WithIntervalSchedule(10, IntervalType.Seconds);
//Executes every 5 minutes
services.AddScheduledJob<MyScheduledJob>().WithIntervalSchedule(5, IntervalType.Minutes);
//Executes every 1 hour
services.AddScheduledJob<MyScheduledJob>().WithIntervalSchedule(1, IntervalType.Hours);
.WithCronSchedule - Defining frequency using CRON
It's possible to define scheduled job timing in more custom way using CRON syntax.
Cron-Expressions are used to configure instances of Scheduled Jobs. 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)
Examples of using CRON schedule
Build a Scheduled Job that will fire every 7 seconds:
services.AddScheduledJob<SlabCreatorScheduledJob>().WithCronSchedule("0/7 * * ? * * *");
Build a Scheduled Job that will fire every other minute, between 8am and 5pm, every day:
services.AddScheduledJob<MyScheduledJob>().WithCronSchedule("0 0/2 8-17 * * ?");
Build a Scheduled Job that will fire daily at 9:30 am:
services.AddScheduledJob<MyScheduledJob>().WithCronSchedule("0 30 9 * * ?");