1Cancel the job where the work is no longer wanted
CancelAsync ends the job as Cancelled: terminal, not a failure, so no retry and no alert.
public sealed class ImportFeedJob
{
[Job("import-feed", MaxAttempts = 5)]
public async Task Handle(ImportFeed feed, JobContext context, CancellationToken ct)
{
if (feed.SourceGone)
{
await context.CancelAsync("source feed no longer exists", ct);
}
Console.WriteLine($"[{feed.Url}] imported");
}
}2Run it and check the output
From a clone of the Acta repository, with the .NET 10 SDK:
dotnet run --project learn/300-failure-and-recovery/302-cancel-jobstatus=CancelledChecked every release. Before each release, Acta Verify runs this program and checks that its output contains these lines.
Remember
CancelAsyncends the job by throwing, so nothing after it runs.Cancelledis not a failure: no retry and no alert follow.
The whole program
Every file of learn/300-failure-and-recovery/302-cancel-job, as it is compiled.
UseLocalDatabase is a helper of the Acta repository, not of the packages. In your own app, register the database with UseSqlite, UsePostgres or UseSqlServer, as in how to run your first job.
cancel-job.cs49 lines
// How to cancel a job from inside its handler
// `CancelAsync` in a handler ends the job as `Cancelled`: terminal, not a failure, so no retry and no alert follow.
using Acta;
using Acta.Learn.CancelJob;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.UseActa(j =>
{
j.UseLocalDatabase(builder.Configuration);
j.Run<CancelJobJobs>("cancel-job");
});
using var host = builder.Build();
await host.StartAsync();
var jobs = host.Services.GetRequiredService<IJobs>();
var outcome = await jobs.EnqueueAsync(new ImportFeed("feed.example.com", SourceGone: true));
await Task.Delay(500);
var snapshot = await jobs.GetAsync(outcome);
Console.WriteLine($"status={snapshot!.Status}");
await host.StopAsync();
namespace Acta.Learn.CancelJob
{
public sealed record ImportFeed(string Url, bool SourceGone);
public sealed class ImportFeedJob
{
[Job("import-feed", MaxAttempts = 5)]
public async Task Handle(ImportFeed feed, JobContext context, CancellationToken ct)
{
if (feed.SourceGone)
{
// learn: Cancel the job where the work is no longer wanted
// CancelAsync ends the job as Cancelled: terminal, not a failure, so no retry and no alert.
await context.CancelAsync("source feed no longer exists", ct);
// learn: end
}
Console.WriteLine($"[{feed.Url}] imported");
}
}
}