``` ├── .github/ ├── workflows/ ├── publish.yml ├── .gitignore ├── LICENSE ├── MinimalWorker.sln ├── README.md ├── assets/ ├── example.png ├── worker.png ├── samples/ ├── MinimalWorker.Api.Sample/ ├── MinimalWorker.Api.Sample.csproj ├── MinimalWorker.Api.Sample.http ├── Program.cs ├── Properties/ ├── launchSettings.json ├── appsettings.Development.json ├── appsettings.json ├── MinimalWorker.Console.Sample/ ├── MinimalWorker.Console.Sample.csproj ├── Program.cs ├── MinimalWorker.Shared.Sample/ ├── ChannelService.cs ├── MinimalWorker.Shared.Sample.csproj ├── src/ ├── MinimalWorker/ ├── BackgroundWorkerExtensions.cs ├── MinimalWorker.csproj ├── assets/ ├── icon.png ├── test/ ├── MinimalWorker.Test/ ├── ICounterService.cs ├── MinimalWorker.Test.csproj ├── MinimalWorkerTests.cs ``` ## /.github/workflows/publish.yml ```yml path="/.github/workflows/publish.yml" name: Publish NuGet Package on: push: tags: - 'v*.*.*' # Trigger only on version tags jobs: build-and-publish: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup .NET uses: actions/setup-dotnet@v4 with: dotnet-version: '9.0.x' - name: Extract version from tag id: get_version run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV - name: Restore dependencies run: dotnet restore MinimalWorker.sln - name: Build run: dotnet build MinimalWorker.sln --configuration Release --no-restore - name: Test NuGet package run: dotnet test MinimalWorker.sln --configuration Release --no-build - name: Pack NuGet package run: dotnet pack src/MinimalWorker --configuration Release --no-build --output ./nupkgs -p:Version=${{ env.VERSION }} - name: Publish to NuGet run: dotnet nuget push ./nupkgs/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json ``` ## /.gitignore ```gitignore path="/.gitignore" ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Mono auto generated files mono_crash.* # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Ww][Ii][Nn]32/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ [Ll]ogs/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUnit *.VisualState.xml TestResult.xml nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # ASP.NET Scaffolding ScaffoldingReadMe.txt # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp # but not Directory.Build.rsp, as it configures directory-level build defaults !Directory.Build.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.tlog *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Coverlet is a free, cross platform Code Coverage Tool coverage*.json coverage*.xml coverage*.info # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # NuGet Symbol Packages *.snupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx *.appxbundle *.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- [Bb]ackup.rdl *- [Bb]ackup ([0-9]).rdl *- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio 6 auto-generated project file (contains which files were open etc.) *.vbp # Visual Studio 6 workspace and project file (working project files containing files to include in project) *.dsw *.dsp # Visual Studio 6 technical files *.ncb *.aps # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # Visual Studio History (VSHistory) files .vshistory/ # BeatPulse healthcheck temp database healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ # Fody - auto-generated XML schema FodyWeavers.xsd # VS Code files for those working on multiple tools .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json *.code-workspace # Local History for Visual Studio Code .history/ # Windows Installer files from build outputs *.cab *.msi *.msix *.msm *.msp # JetBrains Rider *.sln.iml .idea/ ``` ## /LICENSE ``` path="/LICENSE" MIT License Copyright (c) 2025 Joshua Jesper Krægpøth Ryder Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ## /MinimalWorker.sln ```sln path="/MinimalWorker.sln" Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalWorker", "src\MinimalWorker\MinimalWorker.csproj", "{72C19DDE-3A9D-48A0-B127-9D45619EEE14}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalWorker.Console.Sample", "samples\MinimalWorker.Console.Sample\MinimalWorker.Console.Sample.csproj", "{4371890F-A33F-40F1-ACAA-9C253235F44C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalWorker.Api.Sample", "samples\MinimalWorker.Api.Sample\MinimalWorker.Api.Sample.csproj", "{BB4252A3-E441-450B-AAE4-131FAEF08278}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalWorker.Shared.Sample", "samples\MinimalWorker.Shared.Sample\MinimalWorker.Shared.Sample.csproj", "{052ED16E-5E46-43F8-BA73-2328D5A86580}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalWorker.Test", "test\MinimalWorker.Test\MinimalWorker.Test.csproj", "{07EB96F3-D24E-43CB-978C-E091DB31F6E1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {72C19DDE-3A9D-48A0-B127-9D45619EEE14}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {72C19DDE-3A9D-48A0-B127-9D45619EEE14}.Debug|Any CPU.Build.0 = Debug|Any CPU {72C19DDE-3A9D-48A0-B127-9D45619EEE14}.Release|Any CPU.ActiveCfg = Release|Any CPU {72C19DDE-3A9D-48A0-B127-9D45619EEE14}.Release|Any CPU.Build.0 = Release|Any CPU {4371890F-A33F-40F1-ACAA-9C253235F44C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4371890F-A33F-40F1-ACAA-9C253235F44C}.Debug|Any CPU.Build.0 = Debug|Any CPU {4371890F-A33F-40F1-ACAA-9C253235F44C}.Release|Any CPU.ActiveCfg = Release|Any CPU {4371890F-A33F-40F1-ACAA-9C253235F44C}.Release|Any CPU.Build.0 = Release|Any CPU {BB4252A3-E441-450B-AAE4-131FAEF08278}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BB4252A3-E441-450B-AAE4-131FAEF08278}.Debug|Any CPU.Build.0 = Debug|Any CPU {BB4252A3-E441-450B-AAE4-131FAEF08278}.Release|Any CPU.ActiveCfg = Release|Any CPU {BB4252A3-E441-450B-AAE4-131FAEF08278}.Release|Any CPU.Build.0 = Release|Any CPU {052ED16E-5E46-43F8-BA73-2328D5A86580}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {052ED16E-5E46-43F8-BA73-2328D5A86580}.Debug|Any CPU.Build.0 = Debug|Any CPU {052ED16E-5E46-43F8-BA73-2328D5A86580}.Release|Any CPU.ActiveCfg = Release|Any CPU {052ED16E-5E46-43F8-BA73-2328D5A86580}.Release|Any CPU.Build.0 = Release|Any CPU {07EB96F3-D24E-43CB-978C-E091DB31F6E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {07EB96F3-D24E-43CB-978C-E091DB31F6E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {07EB96F3-D24E-43CB-978C-E091DB31F6E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {07EB96F3-D24E-43CB-978C-E091DB31F6E1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal ``` ## /README.md # MinimalWorker [![Publish NuGet Package](https://github.com/TopSwagCode/MinimalWorker/actions/workflows/publish.yml/badge.svg)](https://github.com/TopSwagCode/MinimalWorker/actions/workflows/publish.yml) ![NuGet Downloads](https://img.shields.io/nuget/dt/MinimalWorker) ![NuGet Version](https://img.shields.io/nuget/v/MinimalWorker) ![Worker](https://raw.githubusercontent.com/TopSwagCode/MinimalWorker/master/assets/worker.png) **MinimalWorker** is a lightweight .NET library that simplifies background worker registration in ASP.NET Core and .NET applications using the `IHost` interface. It offers two simple extension methods to map background tasks that run continuously or periodically, with support for dependency injection and cancellation tokens. --- ## ✨ Features - 🚀 Register background workers with a single method call - ⏱ Support for periodic background tasks - 🔄 Built-in support for `CancellationToken` - 🧪 Works seamlessly with dependency injection (`IServiceProvider`) - 🧼 Minimal and clean API --- ## 📦 Installation Install from NuGet: ```bash dotnet add package MinimalWorker ``` Or via the NuGet Package Manager: ```powershell Install-Package MinimalWorker ``` ## 🛠 Usage ### Continuous Background Worker ```csharp app.MapBackgroundWorker(async (MyService service, CancellationToken token) => { while (!token.IsCancellationRequested) { await service.DoWorkAsync(); await Task.Delay(1000, token); } }); ``` ### Periodic Background Worker ```csharp app.MapPeriodicBackgroundWorker(TimeSpan.FromMinutes(5), async (MyService service, CancellationToken token) => { await service.CleanupAsync(); }); ``` ### Command run on notice (Cron) Background Worker ```csharp app.MapCronBackgroundWorker("0 0 * * *", async (CancellationToken ct, MyService service) => { await service.SendDailyProgressReport(); }); ``` All methods automatically resolve services from the DI container and inject the `CancellationToken` if it's a parameter. ## 🔧 How It Works - `MapBackgroundWorker` runs a background task once the application starts, and continues until shutdown. - `MapPeriodicBackgroundWorker` runs your task repeatedly at a fixed interval using PeriodicTimer. - `MapCronBackgroundWorker` runs your task repeatedly based on a CRON expression (UTC time), using NCrontab for timing. - Services and parameters are resolved per execution using `CreateScope()` to support scoped dependencies. ## /assets/example.png Binary file available at https://raw.githubusercontent.com/TopSwagCode/MinimalWorker/refs/heads/main/assets/example.png ## /assets/worker.png Binary file available at https://raw.githubusercontent.com/TopSwagCode/MinimalWorker/refs/heads/main/assets/worker.png ## /samples/MinimalWorker.Api.Sample/MinimalWorker.Api.Sample.csproj ```csproj path="/samples/MinimalWorker.Api.Sample/MinimalWorker.Api.Sample.csproj" net9.0 enable enable ``` ## /samples/MinimalWorker.Api.Sample/MinimalWorker.Api.Sample.http ```http path="/samples/MinimalWorker.Api.Sample/MinimalWorker.Api.Sample.http" @MinimalWorker.Api.Sample_HostAddress = http://localhost:5198 GET {{MinimalWorker.Api.Sample_HostAddress}}/weatherforecast/ Accept: application/json ### ``` ## /samples/MinimalWorker.Api.Sample/Program.cs ```cs path="/samples/MinimalWorker.Api.Sample/Program.cs" using MinimalWorker; using MinimalWorker.Shared.Sample; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); builder.Services.AddSingleton(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.MapOpenApi(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", async (ChannelService channelService) => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); await channelService.SendNotificationAsync("Hello from Api!"); return forecast; }) .WithName("GetWeatherForecast"); app.MapBackgroundWorker(async (CancellationToken ct, ChannelService channelService) => { await foreach (var str in channelService.ReadAllNotificationsAsync(ct)) { Console.WriteLine("Background worker running at {0}", DateTime.Now); } }); app.Run(); record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); } ``` ## /samples/MinimalWorker.Api.Sample/Properties/launchSettings.json ```json path="/samples/MinimalWorker.Api.Sample/Properties/launchSettings.json" { "$schema": "https://json.schemastore.org/launchsettings.json", "profiles": { "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "applicationUrl": "http://localhost:5198", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "https": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "applicationUrl": "https://localhost:7240;http://localhost:5198", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ``` ## /samples/MinimalWorker.Api.Sample/appsettings.Development.json ```json path="/samples/MinimalWorker.Api.Sample/appsettings.Development.json" { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } } } ``` ## /samples/MinimalWorker.Api.Sample/appsettings.json ```json path="/samples/MinimalWorker.Api.Sample/appsettings.json" { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } ``` ## /samples/MinimalWorker.Console.Sample/MinimalWorker.Console.Sample.csproj ```csproj path="/samples/MinimalWorker.Console.Sample/MinimalWorker.Console.Sample.csproj" Exe net9.0 enable enable ``` ## /samples/MinimalWorker.Console.Sample/Program.cs ```cs path="/samples/MinimalWorker.Console.Sample/Program.cs" using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MinimalWorker; using MinimalWorker.Shared.Sample; var builder = Host.CreateApplicationBuilder(args); builder.Services.AddSingleton(); var app = builder.Build(); app.MapBackgroundWorker(async (CancellationToken ct, ChannelService channelService) => { await foreach (var str in channelService.ReadAllNotificationsAsync(ct)) { Console.WriteLine("Background worker running at {0}", DateTime.Now); } }); app.MapPeriodicBackgroundWorker(TimeSpan.FromSeconds(1), async (CancellationToken ct, ChannelService channelService) => { Console.WriteLine("Periodic Background worker running at {0}", DateTime.Now); await channelService.SendNotificationAsync("Hello from Periodic Background worker!"); }); app.MapCronBackgroundWorker("* * * * *", async (CancellationToken ct, ChannelService channelService) => { Console.WriteLine("Cron Background worker running at {0}", DateTime.Now); await channelService.SendNotificationAsync("Hello from Cron Background worker!"); }); app.Run(); ``` ## /samples/MinimalWorker.Shared.Sample/ChannelService.cs ```cs path="/samples/MinimalWorker.Shared.Sample/ChannelService.cs" using System.Threading.Channels; namespace MinimalWorker.Shared.Sample; public class ChannelService { private readonly Channel _stringChannel = System.Threading.Channels.Channel.CreateUnbounded(); public async Task SendNotificationAsync(string notification) { await _stringChannel.Writer.WriteAsync(notification); } public IAsyncEnumerable ReadAllNotificationsAsync(System.Threading.CancellationToken stoppingToken) { return _stringChannel.Reader.ReadAllAsync(stoppingToken); } } ``` ## /samples/MinimalWorker.Shared.Sample/MinimalWorker.Shared.Sample.csproj ```csproj path="/samples/MinimalWorker.Shared.Sample/MinimalWorker.Shared.Sample.csproj" net9.0 enable enable ``` ## /src/MinimalWorker/BackgroundWorkerExtensions.cs ```cs path="/src/MinimalWorker/BackgroundWorkerExtensions.cs" using System.Reflection; using NCrontab; namespace MinimalWorker; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; public static class BackgroundWorkerExtensions { /// /// Maps a background worker that continuously executes the specified delegate while the application is running. /// /// The to register the background worker on. /// /// A delegate representing the work to be executed. /// It can return a for asynchronous work, or void for synchronous work. /// /// /// The worker will start when the application starts and run in a continuous loop until shutdown. /// Dependency injection is supported for method parameters. /// /// /// Example usage: /// /// host.MapBackgroundWorker(async (CancellationToken token) => /// { /// while (!token.IsCancellationRequested) /// { /// Console.WriteLine("Running background task..."); /// await Task.Delay(1000, token); /// } /// }); /// /// public static void MapBackgroundWorker(this IHost host, Delegate action) { var lifetime = host.Services.GetRequiredService(); var parameters = action.Method.GetParameters(); lifetime.ApplicationStarted.Register(() => { var token = lifetime.ApplicationStopping; _ = Task.Run(async () => { using var scope = host.Services.CreateScope(); var args = GetRequiredArguments(scope.ServiceProvider, parameters, token); while (!token.IsCancellationRequested) { var result = action.DynamicInvoke(args); if (result is Task task) { await task; } } }, token); }); } /// /// Maps a periodic background worker that executes the specified delegate at a fixed time interval. /// /// The to register the background worker on. /// The interval between executions. /// /// A delegate representing the work to be executed periodically. /// It can return a for asynchronous work, or void for synchronous work. /// /// /// The worker starts after the application is started and will execute the action repeatedly based on the specified interval. /// Dependency injection is supported for method parameters. /// /// /// Example usage: /// /// host.MapPeriodicBackgroundWorker(TimeSpan.FromMinutes(5), async (CancellationToken token) => /// { /// Console.WriteLine("Running periodic task every 5 minutes..."); /// await Task.CompletedTask; /// }); /// /// public static void MapPeriodicBackgroundWorker(this IHost host, TimeSpan timespan, Delegate action) { var lifetime = host.Services.GetRequiredService(); var parameters = action.Method.GetParameters(); lifetime.ApplicationStarted.Register(() => { var token = lifetime.ApplicationStopping; _ = Task.Run(async () => { var timer = new PeriodicTimer(timespan); while (await timer.WaitForNextTickAsync(token)) { using var scope = host.Services.CreateScope(); var args = GetRequiredArguments(scope.ServiceProvider, parameters, token); var result = action.DynamicInvoke(args); if (result is Task task) { await task; } } }, token); }); } /// /// Maps a cron-scheduled background worker that executes the specified delegate according to a cron expression. /// /// The to register the background worker on. /// /// A cron expression string defining the schedule. /// Uses the standard cron format (minute, hour, day of month, month, day of week). /// /// /// A delegate representing the work to be executed on the scheduled times. /// It can return a for asynchronous work, or void for synchronous work. /// /// /// The worker schedules the execution based on the next occurrence derived from the cron expression. /// Dependency injection is supported for method parameters. /// /// /// Example usage: /// /// host.MapCronBackgroundWorker("*/15 * * * *", async (CancellationToken token) => /// { /// Console.WriteLine("Running cron task every 15 minutes..."); /// await Task.CompletedTask; /// }); /// /// public static void MapCronBackgroundWorker(this IHost host, string cronExpression, Delegate action) { var lifetime = host.Services.GetRequiredService(); var parameters = action.Method.GetParameters(); var schedule = CrontabSchedule.Parse(cronExpression); lifetime.ApplicationStarted.Register(() => { var token = lifetime.ApplicationStopping; _ = Task.Run(async () => { while (!token.IsCancellationRequested) { var nextRun = schedule.GetNextOccurrence(DateTime.UtcNow); var delay = nextRun - DateTime.UtcNow; if (delay > TimeSpan.Zero) { try { await Task.Delay(delay, token); } catch (TaskCanceledException) { break; } } using var scope = host.Services.CreateScope(); var args = GetRequiredArguments(scope.ServiceProvider, parameters, token); var result = action.DynamicInvoke(args); if (result is Task task) { await task; } } }, token); }); } private static object[] GetRequiredArguments(IServiceProvider serviceProvider, ParameterInfo[] parameters, CancellationToken token) { var args = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType == typeof(CancellationToken)) { args[i] = token; } else { args[i] = serviceProvider.GetRequiredService(parameters[i].ParameterType); } } return args; } } ``` ## /src/MinimalWorker/MinimalWorker.csproj ```csproj path="/src/MinimalWorker/MinimalWorker.csproj" net8.0;net9.0 enable enable Joshua Jesper Krægpøth Ryder TopSwagCode MinimalWorker MinimalWorker is a lightweight .NET library that simplifies background worker registration in ASP.NET Core and .NET applications using the `IHost` interface. It offers two simple extension methods to map background tasks that run continuously or periodically, with support for dependency injection and cancellation tokens. https://github.com/TopSwagCode/MinimalWorker https://github.com/TopSwagCode/MinimalWorker git TopSwagCode, AspNet, AspNetCore, NetCore, Background, Recurring, Tasks MIT Copyright © 2025 Joshua Jesper Krægpøth Ryder README.md icon.png true true true snupkg ``` ## /src/MinimalWorker/assets/icon.png Binary file available at https://raw.githubusercontent.com/TopSwagCode/MinimalWorker/refs/heads/main/src/MinimalWorker/assets/icon.png ## /test/MinimalWorker.Test/ICounterService.cs ```cs path="/test/MinimalWorker.Test/ICounterService.cs" namespace MinimalWorker.Test; public interface ICounterService { void Increment(); } ``` ## /test/MinimalWorker.Test/MinimalWorker.Test.csproj ```csproj path="/test/MinimalWorker.Test/MinimalWorker.Test.csproj" net9.0 enable enable false ``` ## /test/MinimalWorker.Test/MinimalWorkerTests.cs ```cs path="/test/MinimalWorker.Test/MinimalWorkerTests.cs" using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NSubstitute; namespace MinimalWorker.Test; public class MinimalWorkerTests { [Fact] public async Task BackgroundWorker_Should_Respect_CancellationToken() { // Arrange var cancellationObserved = new TaskCompletionSource(); using var host = Host.CreateDefaultBuilder() .Build(); host.MapBackgroundWorker(async (CancellationToken token) => { try { while (!token.IsCancellationRequested) { await Task.Delay(50, token); } } catch (OperationCanceledException) { cancellationObserved.TrySetResult(true); } }); // Act await host.StartAsync(); await Task.Delay(100); await host.StopAsync(); // Assert var wasCancelled = await cancellationObserved.Task.WaitAsync(TimeSpan.FromSeconds(1)); Assert.True(wasCancelled, "The background worker did not observe cancellation properly."); } [Fact] public async Task BackgroundWorker_Should_Resolve_Dependencies_And_Invoke_Action() { // Arrange var service = Substitute.For(); using var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddSingleton(service); }) .Build(); host.MapBackgroundWorker(async (ICounterService myService, CancellationToken token) => { myService.Increment(); await Task.Delay(50, token); return Task.CompletedTask; }); // Act await host.StartAsync(); await Task.Delay(95); await host.StopAsync(); // Assert service.Received(2).Increment(); } [Fact] public async Task PeriodicBackgroundWorker_Should_Invoke_Action_Multiple_Times() { // Arrange var counter = Substitute.For(); using var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddSingleton(counter); }) .Build(); host.MapPeriodicBackgroundWorker(TimeSpan.FromMilliseconds(50), (ICounterService svc, CancellationToken token) => { svc.Increment(); return Task.CompletedTask; }); // Act await host.StartAsync(); await Task.Delay(303); // 3 as buffer await host.StopAsync(); // Assert counter.Received(6).Increment(); } [Fact(Skip = "Slow test, run manually if needed")] public async Task CronBackgroundWorker_Should_Invoke_Action_At_Scheduled_Times() { // Arrange var service = Substitute.For(); using var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddSingleton(service); }) .Build(); host.MapCronBackgroundWorker("* * * * *", (ICounterService svc, CancellationToken token) => { svc.Increment(); return Task.CompletedTask; }); // Act await host.StartAsync(); await Task.Delay(61000); await host.StopAsync(); // Assert service.Received(1).Increment(); } } ``` The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.