Calabonga.Microservices.BackgroundWorkers 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Calabonga.Microservices.BackgroundWorkers --version 3.0.0
                    
NuGet\Install-Package Calabonga.Microservices.BackgroundWorkers -Version 3.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Calabonga.Microservices.BackgroundWorkers" Version="3.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Calabonga.Microservices.BackgroundWorkers" Version="3.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Calabonga.Microservices.BackgroundWorkers" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Calabonga.Microservices.BackgroundWorkers --version 3.0.0
                    
#r "nuget: Calabonga.Microservices.BackgroundWorkers, 3.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Calabonga.Microservices.BackgroundWorkers@3.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Calabonga.Microservices.BackgroundWorkers&version=3.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Calabonga.Microservices.BackgroundWorkers&version=3.0.0
                    
Install as a Cake Tool

BackgroundWorkers

Background Workers for Microservices on ASP.NET Core. Contains Scoped and Scheduled workers

Installation and sample

You can install from nuget-package Calabonga.Microservices.BackgroundWorkers. Also you can see the using sample on the github

dotnet add package Calabonga.Microservices.BackgroundWorkers

How it works

Scoped worker. ScopedHostedServiceBase is an IHostedService that runs your code in an endless loop with a 5-second pause between iterations until the application stops. Every iteration gets its own DI scope, so you can safely resolve scoped services such as DbContext from the serviceProvider argument. An exception thrown inside an iteration is logged with the ILogger you passed to the constructor, and the worker keeps running; only cancellation on application shutdown stops the loop.

public sealed class CleanupWorker : ScopedHostedServiceBase
{
    public CleanupWorker(IServiceScopeFactory serviceScopeFactory, ILogger<CleanupWorker> logger)
        : base(serviceScopeFactory, logger) { }

    protected override async Task ProcessInScopeAsync(IServiceProvider serviceProvider, CancellationToken token)
    {
        var repository = serviceProvider.GetRequiredService<IOrderRepository>();
        await repository.DeleteExpiredAsync(token);
    }
}

Scheduled worker. ScheduledHostedServiceBase adds a CronTab schedule on top of the scoped worker: it checks the schedule every 5 seconds and calls ProcessInScopeAsync when the next occurrence has come. Provide the cron expression in Schedule and a name in DisplayName. Set IncludingSeconds to true to use the 6-field format with seconds, and IsExecuteOnServerRestart to true to run once 5 seconds after the application starts. Since version 3.0.0 the schedule and the public NextRun property are in UTC, not in the server's local time. Missed occurrences are not replayed, and the schedule accuracy is about 5 seconds. The schedule is parsed in the base constructor, so overridden properties must return constant values and must not depend on fields of your class.

public sealed class DailyReportWorker : ScheduledHostedServiceBase
{
    public DailyReportWorker(IServiceScopeFactory serviceScopeFactory, ILogger<DailyReportWorker> logger)
        : base(serviceScopeFactory, logger) { }

    // every day at 03:00 UTC
    protected override string Schedule => "0 3 * * *";

    protected override string DisplayName => "Daily report";

    protected override bool IsExecuteOnServerRestart => true;

    protected override async Task ProcessInScopeAsync(IServiceProvider serviceProvider, CancellationToken token)
    {
        var reports = serviceProvider.GetRequiredService<IReportService>();
        await reports.BuildDailyReportAsync(token);
    }
}

Registration. Workers are ordinary hosted services, so register them with AddHostedService<T>(): the host starts them together with the application and cancels them on shutdown. The library targets netstandard2.1 and depends only on Microsoft.Extensions.*.Abstractions and ncrontab, so it works with any .NET host, not only ASP.NET Core. For a custom loop you can inherit HostedServiceBase directly and override ProcessAsync (and ExecuteAsync to change the timing).

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHostedService<CleanupWorker>();
builder.Services.AddHostedService<DailyReportWorker>();

var app = builder.Build();
app.Run();
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.2.1 228 10/4/2026
3.2.0 132 9/27/2026
3.1.0 100 9/27/2026
3.0.0 110 9/27/2026
2.0.3 1,948 6/28/2023
2.0.2 1,663 2/9/2023
2.0.1 916 2/9/2023
2.0.0 917 2/9/2023
1.0.5 1,890 12/3/2021
1.0.4 2,248 10/8/2020
1.0.3 1,250 10/6/2020
1.0.2 1,198 9/24/2020
1.0.1 1,488 9/3/2020
1.0.0 1,535 8/3/2020
1.0.0-beta2 1,054 4/20/2020
1.0.0-beta1 1,108 4/20/2020

BREAKING: schedule and NextRun are now in UTC. C# 10.0 with file-scoped namespaces. Microsoft.Extensions.*.Abstractions updated to 10.0.12.