Background Jobs
StartSharp runs background jobs inside the web application: jobs that run at an interval, at a time of day, by a cron expression, or only when someone starts them, without a Windows service or a scheduled task to install on every server. The background job manager of Pro.Extensions schedules them, keeps the history of their runs with the lines they log, and makes sure that only one server of an application runs a schedule at a time. Administrators see and control them on the Background Jobs page (Administration / Background Jobs).
Turning Them On
// Startup.cs
services.AddBackgroundJobs()
.AddBackgroundJobStore();
// appsettings.json
"BackgroundJobs": {
"Enabled": true
}
AddBackgroundJobs()registers the manager, and a hosted service that gives it the jobs registered as services when the application starts.AddBackgroundJobStore()keeps the schedules and the runs in thejob_Schedulesandjob_Runstables, which the migrations of Pro.Extensions create under theProBackgroundJobsconnection key (falling back toProExtensions,ProFeaturesandDefault). Without it, they are kept in memory: changes made on the page are lost when the application restarts, and every server runs every job. The scheduled reports need the store.- Nothing runs while
BackgroundJobs:Enabledis false, e.g. on a developer machine.
Writing a Job
A job derives from BackgroundJob and is registered as a service:
public class NightlyImportJob(IOrderImporter importer) : BackgroundJob
{
public override string Title => "Nightly import";
public override JobSchedule DefaultSchedule => JobSchedule.DailyAt(2, 30);
public override async Task ExecuteAsync(BackgroundJobContext context, CancellationToken cancellationToken)
{
var count = await importer.ImportAsync(cancellationToken);
context.Log.LogInformation("Imported {count} orders", count);
context.Message = $"{count} orders";
}
}
services.AddBackgroundJob<NightlyImportJob>();
The job is a singleton. For scoped services, e.g. a unit of work, create a scope in ExecuteAsync with
IServiceProvider.CreateAsyncScope().
| Member | What it is |
|---|---|
Key |
What its schedules and runs are stored by; the name of its type by default. Keep it the same between versions. |
Title, Description |
Shown on the page; a text or the key of a local text. |
DefaultSchedule |
When it runs unless an administrator changes it on the page. JobSchedule.Manual by default. |
MaxRetries, RetryDelay |
How often a failed run is tried again (0 by default), and after how long (10 minutes). |
CanCancel |
Whether a run stops when its cancellation token is canceled, so the page offers Stop. True by default. |
AllowMultipleSchedules |
Whether it can have more schedules than its own, each with a title and parameters. |
Schedules
A schedule is one text, in the code, the database and the page alike:
| Text | Runs |
|---|---|
@every 30s, @every 1h30m |
At an interval (s, m, h, d), counted from the start of the run before. |
30 2 * * 1-5 |
By a cron expression of five fields (minute, hour, day of month, month, day of week): lists, ranges, steps, names like MON, L for the last day of the month. |
@hourly, @daily, @weekly, @monthly, @yearly |
Short forms of cron expressions. |
@manual |
Only when someone starts it. |
In code: JobSchedule.Every(TimeSpan.FromMinutes(5)), JobSchedule.DailyAt(2, 30), JobSchedule.Cron("30 2 * * 1-5"),
JobSchedule.Parse(text).
- The times of day are on the clock of the schedule's time zone, e.g.
Europe/Istanbul, which the schedule dialog has a field for. A schedule without one usesBackgroundJobs:TimeZone, or the server's time zone. A time the clock skips when it goes forward runs as late as the clock moved, and one it repeats when it goes back runs once. - A run that was missed while the application was down runs once when it starts. A run that someone starts does not move the next scheduled one.
What a Run Gets
ExecuteAsync gets a BackgroundJobContext:
| Property | What it is |
|---|---|
Log |
The logger of the run. What is logged during the run, through it or any other ILogger, is kept with the run and shown on the page, up to MaxRunLogLines lines of RunLogLevel or above. |
Message |
A short result for the history, e.g. "12 emails sent". Runs that succeed with no message and no log lines are counted on one entry instead of filling the history, so leave it empty when there was nothing to do. |
Skipped |
Set it when the run did nothing on purpose, e.g. a report with no rows that is not sent; the run is recorded as Skipped. |
Parameters, GetParameters<T>() |
The parameters of the schedule, as JSON, for a job with AllowMultipleSchedules. |
Owner |
The user the schedule runs as, see below, or null. |
TimeZone |
The time zone of the schedule. |
LastStart |
When the run before started, e.g. for a job that handles what happened since then. |
Trigger, TriggeredByUsername |
Whether the schedule, a person or a retry started it. |
An exception fails the run. It is logged as an error, so it reaches the exception log, and the run on the page links to it there.
Running as a User
A schedule can have an owner, the Runs as field of the schedule dialog. The run then acts as that user, through the
user accessor of the application, so the permissions of the user apply to what the job does, e.g. to a report it runs,
and context.Owner has the user. Without an owner, a job runs without a user. A run whose owner is not found or is not
active fails instead of running without the user. The scheduled reports of the reports page use this: each runs as the
user who scheduled it.
Several Servers
With the database store, the servers of an application that share the database share the schedules. A schedule that is
due is run by the server that takes it first, which holds it for LockSeconds (120) and renews it while the run goes on.
When a server stops in the middle of a run, another one takes the schedule over after that time, and the run is shown as
Abandoned with the log lines it had written. The lines of a run that goes on are written every RunLogFlushSeconds
(10), so they can be read on the page before it ends.
Settings
The BackgroundJobs section of appsettings.json:
| Setting | Default | |
|---|---|---|
Enabled |
false |
Whether jobs run at all. |
PollSeconds |
10 |
How often the manager looks for schedules that are due. |
TimeZone |
the server's | The time zone of the schedules that have none of their own. |
LockSeconds |
120 |
How long a server holds a schedule it runs without renewing it. |
RunRetentionDays |
30 |
How long the runs are kept. |
MaxRunsPerSchedule |
200 |
The most runs kept for a schedule. |
MaxRunLogLines |
500 |
The most log lines kept for a run. |
RunLogFlushSeconds |
10 |
How often the log lines of a run that goes on are written; 0 for only at its end. |
RunLogLevel |
Information |
The lowest level of the log lines that are kept. |
ConnectionKey |
ProBackgroundJobs |
The connection of the tables of the store. |
Jobs That Come With StartSharp
| Job | Default schedule | |
|---|---|---|
| Email queue | every 30 seconds | Sends the queued emails, see Email Queue. Pausing the queue on its page turns this schedule off. |
| Email queue cleanup | every 6 hours | Removes the old sent, failed and cancelled emails. |
| Exception log cleanup | every 6 hours | Removes the old events, counters and issues of the exception log. |
| Exception log notifications | every 5 minutes | Emails the new and the regressed issues, when turned on in the settings. |
| Account activity cleanup, Session cleanup | every hour | Remove the old sign-ins, account changes and sessions. |
| Report schedules | only when started | Runs the reports that users scheduled on the reports page, one schedule each. |
Older Jobs
Jobs that derive from PeriodicBackgroundJob or DailyBackgroundJob keep working without a change: the manager
schedules them by their interval or their time of day, and they appear on the page with their history. They can't be
stopped while they run, as InternalRun gets no cancellation token. A job that only implements IBackgroundJob still
schedules itself, is asked to process on every look of the manager, and is listed without actions.
app.UseBackgroundJob<TJob>() still registers a job, though services.AddBackgroundJob<TJob>() is simpler.