DotNetBrightener.Core.BackgroundTasks 2025.0.10

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package DotNetBrightener.Core.BackgroundTasks --version 2025.0.10
                    
NuGet\Install-Package DotNetBrightener.Core.BackgroundTasks -Version 2025.0.10
                    
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="DotNetBrightener.Core.BackgroundTasks" Version="2025.0.10" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DotNetBrightener.Core.BackgroundTasks" Version="2025.0.10" />
                    
Directory.Packages.props
<PackageReference Include="DotNetBrightener.Core.BackgroundTasks" />
                    
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 DotNetBrightener.Core.BackgroundTasks --version 2025.0.10
                    
#r "nuget: DotNetBrightener.Core.BackgroundTasks, 2025.0.10"
                    
#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 DotNetBrightener.Core.BackgroundTasks@2025.0.10
                    
#: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=DotNetBrightener.Core.BackgroundTasks&version=2025.0.10
                    
Install as a Cake Addin
#tool nuget:?package=DotNetBrightener.Core.BackgroundTasks&version=2025.0.10
                    
Install as a Cake Tool

DotNetBrightener Background Tasks

Overview

The DotNetBrightener Background Tasks module provides a comprehensive, cron-based task scheduling system for .NET applications. It enables developers to schedule and execute background tasks with precise timing control, overlap prevention, and robust error handling.

Key Features

  • Flexible Scheduling: Support for cron expressions, predefined intervals, and one-time execution
  • Overlap Prevention: Built-in locking mechanism to prevent concurrent execution of the same task
  • Multiple Task Types: Support for both interface-based tasks (IBackgroundTask) and method-based tasks
  • Event-Driven Architecture: Integration with EventPubSub system for task lifecycle events
  • Database Persistence: Optional database storage for task definitions and execution history
  • Timezone Support: Execute tasks in specific timezones
  • Conditional Execution: Execute tasks based on custom predicates
  • Dependency Injection: Full integration with .NET's dependency injection container
  • Comprehensive Logging: Detailed logging for monitoring and debugging

Architecture

Core Components

IScheduler

The main interface for scheduling and managing background tasks. Provides methods to:

  • Schedule tasks by type or method
  • Execute tasks at specific times
  • Cancel running tasks
  • Unschedule tasks
IBackgroundTask

Interface that background task classes must implement:

public interface IBackgroundTask
{
    Task Execute();
}
ICancellableTask

Extended interface for tasks that support cancellation:

public interface ICancellableTask : IBackgroundTask
{
    CancellationToken CancellationToken { get; set; }
}
IScheduleConfig

Fluent interface for configuring task schedules with methods like:

  • EverySecond(), EveryMinute(), Hourly(), Daily()
  • Cron(string expression)
  • PreventOverlapping()
  • When(Func<Task<bool>> predicate)
  • AtTimeZone(TimeZoneInfo timeZoneInfo)

Task Execution Flow

  1. SchedulerHostedService runs every second
  2. Scheduler checks all registered tasks for due execution
  3. Tasks are executed in parallel with proper scoping
  4. Events are published for task lifecycle (Started, Ended, Failed)
  5. Overlap prevention is enforced if configured
  6. Results and errors are logged

Getting Started

1. Installation and Setup

Add the background tasks services to your application:

var builder = WebApplication.CreateBuilder(args);

// Enable background task services
builder.Services.EnableBackgroundTaskServices(builder.Configuration);

var app = builder.Build();

2. Creating Background Tasks

Interface-Based Tasks
public class EmailCleanupTask : IBackgroundTask
{
    private readonly IEmailService _emailService;
    private readonly ILogger<EmailCleanupTask> _logger;

    public EmailCleanupTask(IEmailService emailService, ILogger<EmailCleanupTask> logger)
    {
        _emailService = emailService;
        _logger = logger;
    }

    public async Task Execute()
    {
        _logger.LogInformation("Starting email cleanup task");
        await _emailService.DeleteOldEmails();
        _logger.LogInformation("Email cleanup task completed");
    }
}
Cancellable Tasks
public class DataProcessingTask : ICancellableTask
{
    public CancellationToken CancellationToken { get; set; }
    
    public async Task Execute()
    {
        while (!CancellationToken.IsCancellationRequested)
        {
            // Process data
            await ProcessBatch();
            await Task.Delay(1000, CancellationToken);
        }
    }
}

3. Registering Tasks

// Register background tasks
builder.Services.AddBackgroundTask<EmailCleanupTask>();
builder.Services.AddBackgroundTask<DataProcessingTask>();

4. Scheduling Tasks

var scheduler = app.Services.GetService<IScheduler>();

// Schedule with predefined intervals
scheduler.ScheduleTask<EmailCleanupTask>()
         .Daily()
         .PreventOverlapping();

// Schedule with custom intervals
scheduler.ScheduleTask<DataProcessingTask>()
         .EverySeconds(30)
         .PreventOverlapping();

// Schedule with cron expressions
scheduler.ScheduleTask<EmailCleanupTask>()
         .Cron("0 2 * * *") // Daily at 2 AM
         .AtTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

// One-time execution
scheduler.ScheduleTask<DataProcessingTask>()
         .Once();

Advanced Features

Method-Based Scheduling

You can schedule methods directly without implementing IBackgroundTask:

public class UtilityService
{
    public async Task CleanupTempFiles()
    {
        // Cleanup logic
    }
    
    public void GenerateReports()
    {
        // Report generation logic
    }
}

// Schedule methods
var methodInfo = typeof(UtilityService).GetMethod(nameof(UtilityService.CleanupTempFiles));
scheduler.ScheduleTask(methodInfo)
         .Hourly()
         .PreventOverlapping();

Conditional Execution

Execute tasks only when certain conditions are met:

scheduler.ScheduleTask<BackupTask>()
         .Daily()
         .When(async () => await IsMaintenanceWindowOpen())
         .PreventOverlapping();

Timezone-Aware Scheduling

scheduler.ScheduleTask<ReportTask>()
         .DailyAt(9, 0) // 9:00 AM
         .AtTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));

Configuration

Basic Configuration

Configure the scheduler interval in appsettings.json:

{
  "BackgroundTaskOptions": {
    "Interval": "00:00:30"
  }
}

Database Storage (Optional)

For persistent task definitions and execution history:

builder.Services.AddBackgroundTaskStorage(options =>
{
    options.UseSqlServer(connectionString);
});

This creates a BackgroundTaskDefinition table to store:

  • Task assembly and type information
  • Cron expressions and timezone settings
  • Execution history and error logs
  • Enable/disable status

Event System Integration

The background tasks system publishes events through the EventPubSub system:

Available Events

  • ScheduledEventStarted: Published when a task begins execution
  • ScheduledEventEnded: Published when a task completes successfully
  • ScheduledEventFailed: Published when a task throws an exception

Event Handlers

public class TaskMonitoringHandler : IEventHandler<ScheduledEventFailed>
{
    public async Task<bool> HandleEvent(ScheduledEventFailed eventMessage)
    {
        // Log error, send notifications, etc.
        return true;
    }
}

Scheduling Options Reference

Predefined Intervals

  • EverySecond() - Every second
  • EverySeconds(int seconds) - Every N seconds
  • EveryMinute() - Every minute
  • EveryFiveMinutes() - Every 5 minutes
  • EveryTenMinutes() - Every 10 minutes
  • EveryFifteenMinutes() - Every 15 minutes
  • EveryThirtyMinutes() - Every 30 minutes
  • Hourly() - Every hour
  • HourlyAt(int minute) - Every hour at specified minute
  • Daily() - Every day at midnight
  • DailyAt(int hour, int minute) - Every day at specified time
  • Weekly() - Every week
  • Monthly() - Every month

Day-of-Week Restrictions

  • Monday(), Tuesday(), Wednesday(), Thursday(), Friday(), Saturday(), Sunday()
  • Weekday() - Monday through Friday
  • Weekend() - Saturday and Sunday

Cron Expressions

Support for standard 5 or 6-part cron expressions:

  • 5-part: minute hour day month weekday
  • 6-part: second minute hour day month weekday

Examples:

  • "0 2 * * *" - Daily at 2:00 AM
  • "*/15 * * * *" - Every 15 minutes
  • "0 0 * * 0" - Every Sunday at midnight
  • "30 14 1 * *" - 2:30 PM on the 1st of every month

Error Handling and Monitoring

Logging

The system provides comprehensive logging at various levels:

  • Task execution start/end
  • Error details with stack traces
  • Performance metrics (execution duration)
  • Overlap prevention actions

Exception Handling

  • Exceptions in tasks are caught and logged
  • Failed tasks don't affect other scheduled tasks
  • ScheduledEventFailed events are published for monitoring

Performance Monitoring

  • Execution duration tracking
  • Concurrent execution monitoring
  • Scheduler iteration counts

Best Practices

  1. Use Dependency Injection: Register tasks as scoped services for proper resource management
  2. Implement Proper Logging: Use structured logging for better monitoring
  3. Handle Cancellation: Implement ICancellableTask for long-running tasks
  4. Prevent Overlapping: Use PreventOverlapping() for tasks that shouldn't run concurrently
  5. Use Appropriate Intervals: Don't over-schedule tasks; consider system resources
  6. Monitor Performance: Watch execution times and adjust schedules accordingly
  7. Handle Exceptions: Implement proper error handling within tasks
  8. Use Timezone Awareness: Specify timezones for business-critical scheduling

Troubleshooting

Common Issues

  1. Tasks Not Executing: Check if EnableBackgroundTaskServices() is called
  2. Dependency Resolution Errors: Ensure tasks are registered with AddBackgroundTask<T>()
  3. Overlapping Prevention Not Working: Verify unique identifiers are properly set
  4. Timezone Issues: Use IANA timezone identifiers for cross-platform compatibility

Debugging

Enable detailed logging to troubleshoot issues:

builder.Services.AddLogging(logging =>
{
    logging.SetMinimumLevel(LogLevel.Debug);
    logging.AddConsole();
});

Migration and Deployment

When using database storage, the system automatically handles database migrations through the MigrateBackgroundTaskDbContextHostedService.

Performance Considerations

  • The scheduler runs every second by default
  • Tasks execute in parallel using separate service scopes
  • Overlap prevention uses in-memory locking with configurable timeouts
  • Database operations are optimized with proper indexing
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on DotNetBrightener.Core.BackgroundTasks:

Package Downloads
DotNetBrightener.WebApp.CommonShared

Package Description

DotNetBrightener.Core.BackgroundTasks.DependencyInjection

Package Description

DotNetBrightener.Core.BackgroundTasks.Data

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.0.1-preview-728 0 1/20/2026
2026.0.1-preview-723 60 1/15/2026
2026.0.1-preview-721 65 1/15/2026
2026.0.1-preview-717 142 1/5/2026
2026.0.1-preview-713 515 12/10/2025
2026.0.1-preview-700 261 12/7/2025
2026.0.1-preview-689 149 12/6/2025
2026.0.1-preview-676 708 12/2/2025
2026.0.1-preview-671 147 11/29/2025
2026.0.1-preview-670 144 11/29/2025
2026.0.1-preview-669 145 11/29/2025
2026.0.1-preview-667 205 11/27/2025
2026.0.1-preview-665 205 11/27/2025
2026.0.1-preview-664 206 11/27/2025
2026.0.1-preview-660 213 11/25/2025
2025.0.10 237 11/25/2025
2025.0.10-preview-628 445 11/20/2025
2025.0.10-preview-605 325 11/17/2025
2025.0.10-preview-602 329 11/17/2025
2025.0.10-preview-581 339 11/11/2025
2025.0.10-preview-559 228 10/29/2025
2025.0.10-preview-557 233 10/27/2025
2025.0.9 241 10/26/2025
2025.0.9-preview-553 220 10/26/2025
2025.0.9-preview-539 161 10/12/2025
2025.0.9-preview-535 228 10/8/2025
2025.0.9-preview-509 246 10/2/2025
2025.0.9-preview-508 228 10/2/2025
2025.0.9-preview-487 252 9/29/2025
2025.0.9-preview-481 218 9/29/2025
2025.0.9-preview-473 202 9/28/2025
2025.0.8 264 9/23/2025
2025.0.6 260 9/22/2025
2025.0.6-preview-455 236 9/22/2025
2025.0.6-preview-454 342 9/17/2025
2025.0.6-preview-441 179 9/14/2025
2025.0.6-preview-440 181 9/14/2025
2025.0.6-preview-406 226 9/2/2025
2025.0.6-preview-401 207 9/2/2025
2025.0.6-preview-400 199 9/2/2025
2025.0.6-preview-369 254 8/27/2025
2025.0.6-preview-368 257 8/27/2025
2025.0.6-preview-334 234 8/18/2025
2025.0.6-preview-333 172 7/27/2025
2025.0.6-preview-332 530 7/24/2025
2025.0.6-preview-331 544 7/24/2025
2025.0.6-preview-328 538 7/24/2025
2025.0.6-preview-327 410 7/21/2025
2025.0.6-preview-326 405 7/21/2025
2025.0.6-preview-325 307 7/20/2025
2025.0.6-preview-324 300 7/20/2025
2025.0.6-preview-322 309 7/20/2025
2025.0.6-preview-321 317 7/19/2025
2025.0.6-preview-320 309 7/19/2025
2025.0.6-preview-319 215 7/17/2025
2025.0.6-preview-317 218 7/17/2025
2025.0.6-preview-316 209 7/17/2025
2025.0.6-preview-315 215 7/17/2025
2025.0.6-preview-314 217 7/17/2025
2025.0.6-preview-313 205 7/17/2025
2025.0.6-preview-312 212 7/16/2025
2025.0.5 249 7/10/2025
2025.0.5-preview-307 154 7/5/2025
2025.0.4 178 7/5/2025
2025.0.4-preview-305 164 7/4/2025
2025.0.4-preview-304 223 7/1/2025
2025.0.4-preview-299 227 5/31/2025
2025.0.4-preview-298 189 5/30/2025
2025.0.4-preview-296 233 5/30/2025
2025.0.4-preview-295 243 5/29/2025
2025.0.4-preview-293 243 5/26/2025
2025.0.4-preview-292 230 5/26/2025
2025.0.3 271 2/10/2025
2025.0.3-preview-288 201 2/10/2025
2025.0.2 249 1/21/2025
2025.0.2-preview-278 189 1/21/2025
2025.0.2-preview-277 197 12/16/2024
2025.0.1-rc-243301701 484 11/25/2024
2024.0.14.6 267 11/25/2024
2024.0.14.6-rc-243031001 283 10/29/2024
2024.0.14.6-rc-243030701 221 10/29/2024
2024.0.14.6-rc-242840501 206 10/10/2024
2024.0.14.6-rc-242820305 208 10/8/2024
2024.0.14.6-rc-242771401 347 10/3/2024
2024.0.14.6-rc-242770501 202 10/3/2024
2024.0.14.6-rc-242770201 226 10/3/2024
2024.0.14.6-rc-242761801 198 10/2/2024
2024.0.14.6-rc-242761601 220 10/2/2024
2024.0.14.6-rc-242761501 199 10/2/2024
2024.0.14.6-rc-242761401 226 10/2/2024
2024.0.14.6-rc-242760701 223 10/2/2024
2024.0.14.6-rc-242751002 215 10/1/2024
2024.0.14.6-rc-242750901 221 10/1/2024
2024.0.14.6-rc-242750502 206 10/1/2024
2024.0.14.6-rc-242750201 214 10/1/2024
2024.0.14.6-rc-242741501 206 9/30/2024
2024.0.14.6-rc-242730701 227 9/29/2024
2024.0.14.6-preview-2730501 204 9/29/2024
2024.0.14.6-preview-2701501 243 9/26/2024
2024.0.14.6-preview-2620901 282 9/18/2024
2024.0.14.6-preview-2570701 249 9/13/2024
2024.0.14.6-preview-2510703 291 9/7/2024
2024.0.14.6-preview-2480501 241 9/4/2024
2024.0.14.6-preview-2430401 245 8/30/2024
2024.0.14.6-preview-242730701 211 9/29/2024
2024.0.14.6-preview-2421703 235 8/29/2024
2024.0.14.6-preview-2421701 206 8/29/2024
2024.0.14.6-preview-2420901 216 8/29/2024
2024.0.14.6-preview-2390101 258 8/26/2024
2024.0.14.6-preview-2381603 250 8/25/2024
2024.0.14.6-preview-2341601 290 8/21/2024
2024.0.14.6-preview-2321602 256 8/20/2024
2024.0.14.6-preview-2190801 266 8/6/2024
2024.0.14.6-preview-2041501 229 7/22/2024
2024.0.14.6-preview-1920603 289 7/10/2024
2024.0.14.6-preview-1920301 224 7/10/2024
2024.0.14.6-preview-1911302 221 7/9/2024
2024.0.14.6-preview-1901001 233 7/8/2024
2024.0.14.6-preview-1900901 211 7/8/2024
2024.0.14.6-preview-1900801 234 7/8/2024
2024.0.14.6-preview-1860304 221 7/4/2024
2024.0.14.5 330 7/1/2024
2024.0.14.5-preview-1811601 238 6/29/2024
2024.0.14.5-preview-1810501 260 6/29/2024
2024.0.14.5-preview-180132 250 6/28/2024
2024.0.14.5-preview-180131 220 6/28/2024
2024.0.14.5-preview-180121 227 6/28/2024
2024.0.14.4 283 6/27/2024
2024.0.14.4-preview-8 196 6/27/2024
2024.0.14.4-preview-7 220 6/27/2024
2024.0.14.3 278 6/21/2024
2024.0.14.1 280 6/6/2024
2024.0.14.1-preview 228 6/6/2024
2024.0.14-preview-1 214 6/6/2024
2024.0.13.8-preview 232 6/6/2024
2024.0.13.2-preview-247 170 6/6/2024
2024.0.13.1-preview-0146 241 6/6/2024
2024.0.13-preview-1 163 6/6/2024
2024.0.12.15803-preview-03 220 6/6/2024
2024.0.12.15608 270 6/4/2024
2024.0.12.15515 357 6/3/2024
2024.0.12.15220 246 5/31/2024
2024.0.12.15220-alpha31-240... 189 5/31/2024
2024.0.12.14911 321 5/28/2024
2024.0.12.14910-alpha28-240... 213 5/28/2024
2024.0.12.14823 286 5/27/2024
2024.0.12.14522-alpha7-2405... 241 5/24/2024
2024.0.12.14514-alpha6-2405... 252 5/24/2024
2024.0.12.14511 292 5/24/2024
2024.0.12.14314 313 5/22/2024
2024.0.12.14114 298 5/20/2024
2024.0.12.12815 329 5/7/2024
2024.0.12.12814 292 5/7/2024
2024.0.12.12721 318 5/6/2024
2024.0.12.12702 280 5/5/2024
2024.0.12.12622 297 5/5/2024
2024.0.12.12514 267 5/4/2024
2024.0.12.12512 293 5/4/2024
2024.0.12.12510 298 5/4/2024
2024.0.12.12420 269 5/3/2024
2024.0.12.12319 236 5/2/2024
2024.0.12.12319-rc-2405021801 171 5/2/2024
2024.0.12.12318 222 5/2/2024
2024.0.12.12215 262 5/1/2024
2024.0.12.12011 269 4/29/2024
2024.0.12.11720 284 4/26/2024
2024.0.12.11719 285 4/26/2024
2024.0.12.11621 305 4/25/2024
2024.0.12.11523 283 4/24/2024
2024.0.12.11522 295 4/24/2024
2024.0.12.11417 282 4/23/2024
2024.0.12.11400 274 4/22/2024
2024.0.12.11316 261 4/22/2024
2024.0.11.10220 251 4/11/2024
2024.0.11.10120 229 4/10/2024
2024.0.11.10119 232 4/10/2024
2024.0.11.10115 211 4/10/2024
2024.0.11.9914 252 4/8/2024
2024.0.11.9901 228 4/7/2024
2024.0.11.9823 236 4/7/2024
2024.0.11.9401 251 4/2/2024
2024.0.11.9301 239 4/1/2024
2024.0.11.9206 268 3/31/2024
2024.0.11.9205 248 3/31/2024
2024.0.11.8200 252 3/21/2024
2024.0.11.8122 218 3/21/2024
2024.0.11.8120 234 3/21/2024
2024.0.11.7320 273 3/13/2024
2024.0.11.7316 236 3/13/2024
2024.0.11.7310 249 3/13/2024
2024.0.11 249 3/13/2024
2024.0.10 285 3/3/2024
2024.0.9 276 2/27/2024
2024.0.8 299 2/1/2024
2024.0.7 241 1/26/2024
2024.0.6 230 1/25/2024
2024.0.5 229 1/24/2024
2024.0.4 227 1/24/2024
2024.0.3 245 1/22/2024
2024.0.2 298 1/10/2024
2024.0.1 248 1/9/2024
2024.0.1-alpha-3 232 1/9/2024
2024.0.1-alpha-2 193 1/9/2024
2024.0.1-alpha-1 222 1/3/2024
2024.0.0 299 12/26/2023
2023.0.27 381 12/21/2023
2023.0.26 274 12/21/2023
2023.0.25 298 12/11/2023
2023.0.24 276 12/8/2023
2023.0.23 242 12/6/2023
2023.0.21 268 12/4/2023
2023.0.20 276 11/27/2023
2023.0.19 257 11/20/2023
2023.0.18 289 10/25/2023
2023.0.17 308 10/22/2023
2023.0.16 342 10/16/2023
2023.0.16-alpha-1 223 10/16/2023
2023.0.15 268 10/14/2023
2023.0.14 246 10/14/2023
2023.0.13 245 10/14/2023
2023.0.12 269 10/14/2023
2023.0.11 238 10/10/2023
2023.0.10 247 10/9/2023
2023.0.9 360 8/16/2023
2023.0.8 274 8/15/2023
2023.0.8-alpha-2 365 5/31/2023
2023.0.7 291 5/12/2023
2023.0.6 496 5/10/2023
2023.0.5 286 5/7/2023
2023.0.4 320 4/22/2023
2023.0.3 351 4/19/2023
2023.0.2 360 4/6/2023
2023.0.1 360 3/13/2023
2022.10.0 408 10/28/2022