Jobs
A background job is a method call that Masterly.NightShift stores and runs later on a server: right away (fire-and-forget), at a given time (delayed), after other jobs (continuations, fan-in, batches), or on a schedule (see Recurring jobs). This section covers how to create one-off jobs, what you can pass to them, how they are canceled, how to find and organize them with tags and notes, how to run them from the dashboard, and how to manage them once they exist.
| Page | What it covers |
|---|---|
| Fire-and-forget jobs | Enqueue in all its forms, queues, Create with an explicit state, BackgroundJobClient, why a job ID can be null |
| Job classes | IJob and IJobHandler<TArgs>: jobs created from a class or an arguments object, with the work in a class of its own |
| Job functions | [JobFunction("name")] and delegates registered in DI, created by name with a checked payload: EnqueueFunction, ScheduleFunction, AddOrUpdateFunction |
| Delayed jobs | Schedule with a TimeSpan, a DateTimeOffset or a plain-English phrase such as "tomorrow at 9am" (TimeText) |
| Schedule policies | Business calendars (days, hours, holidays) stored by name, that move, skip or reject delayed jobs and leave out recurring occurrences |
| Continuations | ContinueJobWith, JobContinuationOptions, passing a parent's result or exception with [FromResult] / [FromException] |
| Chains | JobChain: workflows of steps, branches and joins created together, rerun from a step, replaced, deleted, or created by a recurring job |
| Fan-in and batches | ContinueJobWithAll / ContinueJobWithAny, and BatchJob for groups of jobs with progress and a continuation |
| Job arguments | What can be passed, how arguments are serialized, how the target instance is created, injected parameters, async methods, return values |
| Cancellation | CancellationToken and IJobCancellationToken, server shutdown, deleting a running job |
| Progress, console and checkpoints | IJobConsole: progress bars, console lines, checkpoints and resumable steps (Resume), what happens when the storage fails |
| Tags and notes | [Tag] and JobTags to find jobs by what they are about, JobNotes for notes and acknowledgements |
| Job catalog | The dashboard's Catalog page and the JobCatalog API: run any job method from the browser |
| Managing jobs | Delete, Requeue, Reschedule, ChangeState, every job state, querying jobs through the monitoring API |
| Source-generated invokers | How job methods are called without reflection, [GenerateJobInvokers], turning generation off |
| Testing | Unit tests for code that creates jobs, job classes and filters; integration tests against LocalDB |
The most common example
Inject IBackgroundJobClient and enqueue a call to one of your services. The server creates the service through dependency injection and calls the method in the background:
using Masterly.NightShift;
public class EmailService
{
public void SendWelcome(int userId)
{
// send the e-mail
}
}
app.MapPost("/users/{id:int}/welcome", (int id, IBackgroundJobClient jobs) =>
{
string? jobId = jobs.Enqueue<EmailService>(x => x.SendWelcome(id));
return Results.Accepted(value: new { jobId });
});
Outside dependency injection, the static facade does the same: BackgroundJob.Enqueue<EmailService>(x => x.SendWelcome(id));. Both need storage and a server to be configured first, see Quick start: ASP.NET Core or Quick start: console app or Worker Service.
Which method do I need?
| I want to | Call | Page |
|---|---|---|
| Run a method once, as soon as possible | Enqueue | Fire-and-forget jobs |
| Run it once, later | Schedule with a TimeSpan, a DateTimeOffset or "tomorrow at 9am" | Delayed jobs |
| Run it only on working days or in business hours | Schedule(..., new ScheduleOptions { Policy = "business-hours" }) | Schedule policies |
| Run it after another job finished | ContinueJobWith | Continuations |
| Run it after several jobs, or the first of them | ContinueJobWithAll, ContinueJobWithAny | Fan-in and batches |
| Run a workflow of steps and parallel branches, with a success and a failure path | JobChain.StartWith(...).Then(...).ThenMany(...).ThenAfterAll(...) | Chains |
| Follow a group of jobs and continue after all of them | BatchJob.StartNew, BatchJob.ContinueWith | Fan-in and batches |
| Run it on a schedule | RecurringJob.AddOrUpdate | Recurring jobs |
| Run a job by name, from code that doesn't know its type | EnqueueFunction("name", payload) | Job functions |
| Stop, rerun or move a job | Delete, Requeue, Reschedule, ChangeState | Managing jobs |
| Cancel every pending job of a method or a function | storage.DeletePendingJobs<T>(), DeletePendingFunctionJobs(name) | Managing jobs |
| Read a job's state or result | storage.GetJobState, storage.TryGetResult | Managing jobs |
| Retry every failed job | storage.RequeueFailedJobs | Managing jobs |
Enqueue, Schedule, Create and the ContinueJobWith... methods return the new job's ID as string?. It is null when a client filter canceled the creation (for example [PreventDuplicates] for a duplicate), so check it before you use it.