Skip to content

Jobs

A job is a class with a Perform method. A worker creates it for each run, in a DI scope of its own, calls Perform with the arguments it was published with, and disposes it.

The usual way is to derive from one of the base classes. TJob is the class itself:

Base class Perform
Job<TJob> void Perform()
Job<TJob, TArgs> void Perform(TArgs args)
JobAsync<TJob> Task Perform(CancellationToken cancellationToken)
JobAsync<TJob, TArgs> Task Perform(TArgs args, CancellationToken cancellationToken)
public class ResizeImage(IBlobStore blobs) : JobAsync<ResizeImage, ResizeArgs>
{
public override async Task Perform(ResizeArgs args, CancellationToken cancellationToken)
{
var image = await blobs.ReadAsync(args.Path, cancellationToken);
await blobs.WriteAsync(args.Path + ".thumb", Thumbnail(image, args.Width), cancellationToken);
}
}
public record ResizeArgs(string Path, int Width);

A plain class works too: no base class, just a public Perform method. It takes (), (CancellationToken), (TArgs) or (TArgs, CancellationToken), and returns void, Task or ValueTask:

public class RebuildSearchIndex(ISearchIndex index)
{
public Task Perform(CancellationToken cancellationToken) => index.RebuildAsync(cancellationToken);
}

The constructor’s parameters come from the job’s scope: a scoped DbContext is the job’s own. A job that implements IDisposable or IAsyncDisposable is disposed after its run.

The arguments are serialized with System.Text.Json into the message, without .NET type names: a class or record with properties, a string, a number. Keep them small (ids rather than whole entities), and keep them compatible: during a rolling deployment an app of the old version can run a job published by the new one.

Under trimming or Native AOT, list the arguments types in a JsonSerializerContext: see Trimming and Native AOT.

Only registered jobs can be published and run. Register them on the builder that AddMassiveJobs returns:

builder.Services.AddMassiveJobs()
.WithJobsFromAssemblyOf<ResizeImage>() // every Job/JobAsync class of that project
.WithJob<RebuildSearchIndex>() // a plain class
.WithJob<LegacyImport>("import.legacy"); // with a tag of your choice
  • WithJobsFromAssembly(assembly) and WithJobsFromAssemblyOf<T>() register the concrete classes derived from Job or JobAsync in an assembly. The list is made when the project compiles, by MassiveJobs’ source generator, so nothing is scanned at runtime. Private nested classes can’t be listed (warning MJ0005): make them internal.
  • WithJob<TJob>() registers one class, a plain one too. A class with Perform methods for several argument types needs WithJob<TJob, TArgs>().

A class that can’t be a job is a compile error, not a runtime surprise: see the diagnostics.

Every job is registered under a tag, the name its messages carry: the tag given to WithJob, else the class’s [JobTag("...")], else its full class name (namespace and class).

[JobTag("email.welcome")]
public class SendWelcomeEmail : JobAsync<SendWelcomeEmail, int> { ... }

With an explicit tag you can rename or move the class freely; without one, a rename changes the tag, and messages already in the queues no longer match. Apps that publish a job and apps that run it must register it under the same tag. A worker that gets a tag it doesn’t know holds the message back for a while (for an app that knows it), then moves it to the failed queue: see unknown jobs.

Inject IJobPublisher (it’s scoped) and publish. The call completes when RabbitMQ has confirmed the messages:

await publisher.PublishAsync<ResizeImage, ResizeArgs>(new ResizeArgs(path, 320));
await publisher.PublishAsync<RebuildSearchIndex>(); // no arguments
await publisher.PublishAsync<ResizeImage, ResizeArgs>( // many at once
paths.Select(p => new ResizeArgs(p, 320)));

Every method has a synchronous twin, Publish, which blocks a thread until the broker has confirmed: for code that can’t await (constructors, synchronous interfaces, call chains that aren’t async). Prefer PublishAsync.

To run a job later, pass a TimeSpan or a UTC time: see Scheduling.

Classes derived from Job/JobAsync also have static PublishAsync and Publish methods, with the same overloads, so any code can publish without injecting anything:

await ResizeImage.PublishAsync(new ResizeArgs(path, 320));
await ResizeImage.PublishAsync(new ResizeArgs(path, 320), TimeSpan.FromMinutes(5));
await ResizeImage.PublishAsync(new ResizeArgs(path, 320), cancellationToken);
ResizeImage.Publish(new ResizeArgs(path, 320)); // blocks until the broker has confirmed

They publish through MassiveJobsMediator.DefaultInstance, the same publisher you’d inject. The host sets it up before any hosted service starts and clears it after all have stopped, so your hosted services can publish when they start and stop. (On a host older than 8.0, which doesn’t have those lifecycle events, it’s set up when MassiveJobs itself starts, so a hosted service registered before AddMassiveJobs can’t publish in its StartAsync yet.) What to keep in mind:

  • It’s one instance per process: two hosts in one process (parallel integration tests, for example) share it, and the last one started wins. Inject IJobPublisher there.
  • Code that publishes through it doesn’t show the dependency, and a unit test can’t swap it for a fake.
  • Plain job classes (registered with WithJob, not derived from Job/JobAsync) don’t have these methods.

Every static method also takes an IJobPublisher explicitly: ResizeImage.PublishAsync(args, publisher).

JobBatch collects the jobs published with the static methods and sends them in one go when the batch ends. Inside a batch, PublishAsync returns at once, and every job goes out through the batch’s publisher, even one published with an explicit publisher. The batch flows across await, and a nested batch joins the outer one:

await JobBatch.DoAsync(async () =>
{
foreach (var order in await LoadOrdersAsync())
{
await SendInvoice.PublishAsync(order.Id);
}
});

IJobPublisher.PublishAsync with a list of jobs does the same without the static API.

Publishing to RabbitMQ doesn’t take part in your database transaction. Publish after the data the job needs is committed, or publish just before the commit and let a failed publish (it throws) roll the transaction back. Either way there’s a window where one happened and the other didn’t: see Guarantees.

The CancellationToken a job gets is cancelled when:

  • its timeout is over. A job published with a timeout (jobTimeoutMs, a positive number of milliseconds) that hasn’t finished by then is abandoned a second later and counts as failed (it’s retried). Its task keeps running until it notices the cancellation, and its services (its DI scope) stay usable until it ends.
  • the default 5 seconds are over, for a job published without a timeout. That’s only a signal: such a job isn’t abandoned, and isn’t failed for running longer.
  • the app is stopping and the job didn’t finish in time: see stopping.
// may take a few minutes: give it a timeout, and it runs in the long-running queues
await publisher.PublishAsync<ExportReport, int>(reportId, jobTimeoutMs: 10 * 60 * 1000);

Jobs published with a timeout of 10 seconds or more (LongRunningThreshold) go to the long-running queues, so they don’t hold up short jobs. Pass the token to everything you await: a job that ignores it can’t be stopped.

A synchronous job (Job<…>, or a plain class with a synchronous Perform) runs on the thread pool. Past its timeout it’s abandoned like any other. A Job<…> gets no token, though, so nothing can stop it early: if it may need stopping, make it a JobAsync<…>, or a plain class whose Perform takes a CancellationToken.