Note: Pre-release packages are distributed via feedz.io.
This .NET Core Worker application demonstrates various scheduled jobs and how to use them. It includes examples of background tasks, startup jobs, and scheduled jobs using the CronScheduler library.
If you like or are using this project to learn or start your solution, please give it a star. Thanks!
This application demonstrates how to use scheduled jobs in a .NET Core Worker application. The application leverages the CronScheduler library to manage and execute scheduled tasks. Below are the steps to add and configure scheduled jobs:
This job is a simple test job that logs its execution.
-
Create a Job Class: Implement the
IScheduledJob
interface in your job class. For example:using System; using System.Threading; using System.Threading.Tasks; using CronScheduler.Extensions.Scheduler; using Microsoft.Extensions.Logging; public class MyScheduledJob : IScheduledJob { private readonly ILogger<MyScheduledJob> _logger; public MyScheduledJob(ILogger<MyScheduledJob> logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Name { get; } = nameof(MyScheduledJob); public async Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation("Executing scheduled job: {jobName}", Name); // Your job logic here await Task.CompletedTask; } }
-
Configure Job Options: Create a class that inherits from
SchedulerOptions
to define job-specific options.using CronScheduler.Extensions.Scheduler; public class MyScheduledJobOptions : SchedulerOptions { public string SomeOption { get; set; } = string.Empty; }
-
Register the Job: In your
Program.cs
orStartup.cs
, register the job and its options with the scheduler. Additionally, add a custom error processing for internal errors using an unobserved task exception handler.services.AddScheduler(builder => { builder.AddJob<MyScheduledJob, MyScheduledJobOptions>(); }); // Add a custom error processing for internal errors builder.AddUnobservedTaskExceptionHandler(sp => { var logger = sp.GetRequiredService<ILoggerFactory>().CreateLogger("CronJobs"); return (sender, args) => { logger?.LogError(args.Exception?.Message); args.SetObserved(); }; });
Jobs can also be added on the fly and configured from a database class where the options are stored using the following syntax:
var jobOptions = await _dbContext.JobOptions.FindAsync("TestJob");
_schedulerRegistration.AddOrUpdate(new TestJob(jobOptions, _loggerFactory.CreateLogger<TestJob>()), jobOptions);
Below are sample options for configuring the jobs in the appsettings.json
file:
{
"SchedulerJobs": {
"TestJob": {
"RunImmediately": true,
"CronSchedule": "0/10 * * * * *"
}
}
}
-
Build the Docker Image: Use the following command to build the Docker image.
docker build --pull --rm -f "src/CronSchedulerWorker/Dockerfile" -t cronschedulerworker:latest .
-
Run the Docker Container: Use the following command to run the Docker container.
docker run --rm -d cronschedulerworker:latest
-
Build and Run: Build and run your application using the following commands. The scheduled jobs will be executed based on their configured schedules.
# Navigate to the project directory cd src/CronSchedulerWorker # Build the project dotnet build # Run the project dotnet run