DotNetBrightener.Core.BackgroundTasks
2025.0.6-preview-368
See the version list below for details.
dotnet add package DotNetBrightener.Core.BackgroundTasks --version 2025.0.6-preview-368
NuGet\Install-Package DotNetBrightener.Core.BackgroundTasks -Version 2025.0.6-preview-368
<PackageReference Include="DotNetBrightener.Core.BackgroundTasks" Version="2025.0.6-preview-368" />
<PackageVersion Include="DotNetBrightener.Core.BackgroundTasks" Version="2025.0.6-preview-368" />
<PackageReference Include="DotNetBrightener.Core.BackgroundTasks" />
paket add DotNetBrightener.Core.BackgroundTasks --version 2025.0.6-preview-368
#r "nuget: DotNetBrightener.Core.BackgroundTasks, 2025.0.6-preview-368"
#:package DotNetBrightener.Core.BackgroundTasks@2025.0.6-preview-368
#addin nuget:?package=DotNetBrightener.Core.BackgroundTasks&version=2025.0.6-preview-368&prerelease
#tool nuget:?package=DotNetBrightener.Core.BackgroundTasks&version=2025.0.6-preview-368&prerelease
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
- SchedulerHostedService runs every second
- Scheduler checks all registered tasks for due execution
- Tasks are executed in parallel with proper scoping
- Events are published for task lifecycle (Started, Ended, Failed)
- Overlap prevention is enforced if configured
- 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 executionScheduledEventEnded
: Published when a task completes successfullyScheduledEventFailed
: 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 secondEverySeconds(int seconds)
- Every N secondsEveryMinute()
- Every minuteEveryFiveMinutes()
- Every 5 minutesEveryTenMinutes()
- Every 10 minutesEveryFifteenMinutes()
- Every 15 minutesEveryThirtyMinutes()
- Every 30 minutesHourly()
- Every hourHourlyAt(int minute)
- Every hour at specified minuteDaily()
- Every day at midnightDailyAt(int hour, int minute)
- Every day at specified timeWeekly()
- Every weekMonthly()
- Every month
Day-of-Week Restrictions
Monday()
,Tuesday()
,Wednesday()
,Thursday()
,Friday()
,Saturday()
,Sunday()
Weekday()
- Monday through FridayWeekend()
- 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
- Use Dependency Injection: Register tasks as scoped services for proper resource management
- Implement Proper Logging: Use structured logging for better monitoring
- Handle Cancellation: Implement
ICancellableTask
for long-running tasks - Prevent Overlapping: Use
PreventOverlapping()
for tasks that shouldn't run concurrently - Use Appropriate Intervals: Don't over-schedule tasks; consider system resources
- Monitor Performance: Watch execution times and adjust schedules accordingly
- Handle Exceptions: Implement proper error handling within tasks
- Use Timezone Awareness: Specify timezones for business-critical scheduling
Troubleshooting
Common Issues
- Tasks Not Executing: Check if
EnableBackgroundTaskServices()
is called - Dependency Resolution Errors: Ensure tasks are registered with
AddBackgroundTask<T>()
- Overlapping Prevention Not Working: Verify unique identifiers are properly set
- 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 | Versions 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. |
-
net9.0
- CronExpressionDescriptor (>= 2.44.0)
- DotNetBrightener.Plugins.EventPubSub (>= 2025.0.6-preview-368)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.8)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.8)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.8)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 9.0.8)
- TimeZoneConverter (>= 7.0.0)
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.