Skip to main content

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.

PageWhat it covers
Fire-and-forget jobsEnqueue in all its forms, queues, Create with an explicit state, BackgroundJobClient, why a job ID can be null
Job classesIJob 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 jobsSchedule with a TimeSpan, a DateTimeOffset or a plain-English phrase such as "tomorrow at 9am" (TimeText)
Schedule policiesBusiness calendars (days, hours, holidays) stored by name, that move, skip or reject delayed jobs and leave out recurring occurrences
ContinuationsContinueJobWith, JobContinuationOptions, passing a parent's result or exception with [FromResult] / [FromException]
ChainsJobChain: workflows of steps, branches and joins created together, rerun from a step, replaced, deleted, or created by a recurring job
Fan-in and batchesContinueJobWithAll / ContinueJobWithAny, and BatchJob for groups of jobs with progress and a continuation
Job argumentsWhat can be passed, how arguments are serialized, how the target instance is created, injected parameters, async methods, return values
CancellationCancellationToken and IJobCancellationToken, server shutdown, deleting a running job
Progress, console and checkpointsIJobConsole: 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 catalogThe dashboard's Catalog page and the JobCatalog API: run any job method from the browser
Managing jobsDelete, Requeue, Reschedule, ChangeState, every job state, querying jobs through the monitoring API
Source-generated invokersHow job methods are called without reflection, [GenerateJobInvokers], turning generation off
TestingUnit 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 toCallPage
Run a method once, as soon as possibleEnqueueFire-and-forget jobs
Run it once, laterSchedule with a TimeSpan, a DateTimeOffset or "tomorrow at 9am"Delayed jobs
Run it only on working days or in business hoursSchedule(..., new ScheduleOptions { Policy = "business-hours" })Schedule policies
Run it after another job finishedContinueJobWithContinuations
Run it after several jobs, or the first of themContinueJobWithAll, ContinueJobWithAnyFan-in and batches
Run a workflow of steps and parallel branches, with a success and a failure pathJobChain.StartWith(...).Then(...).ThenMany(...).ThenAfterAll(...)Chains
Follow a group of jobs and continue after all of themBatchJob.StartNew, BatchJob.ContinueWithFan-in and batches
Run it on a scheduleRecurringJob.AddOrUpdateRecurring jobs
Run a job by name, from code that doesn't know its typeEnqueueFunction("name", payload)Job functions
Stop, rerun or move a jobDelete, Requeue, Reschedule, ChangeStateManaging jobs
Cancel every pending job of a method or a functionstorage.DeletePendingJobs<T>(), DeletePendingFunctionJobs(name)Managing jobs
Read a job's state or resultstorage.GetJobState, storage.TryGetResultManaging jobs
Retry every failed jobstorage.RequeueFailedJobsManaging 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.

See also​