### Install CronScheduler.AspNetCore Package Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Use this command to install the CronScheduler.AspNetCore package for AspNetCore hosting. ```bash dotnet add package CronScheduler.AspNetCore ``` -------------------------------- ### Install CronScheduler.Extensions Package Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Use this command to install the CronScheduler.Extensions package for IHost hosting. ```bash dotnet add package CronScheduler.Extensions ``` -------------------------------- ### Add Startup Jobs in Program.cs Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Register and run startup jobs before the application starts. Ensure services are added to the container and then run startup jobs using `RunStartupJobsAsync`. ```csharp var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddStartupJob(); builder.Services.AddStartupJob(); var app = builder.Build(); // Configure the HTTP request pipeline. await app.RunStartupJobsAsync(); await app.RunAsync(); ``` -------------------------------- ### Sample appsettings.json for Scheduler Jobs Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerWorker/README.md Configure job schedules and runtime behavior using the 'SchedulerJobs' section in your appsettings.json file. This example shows a job that runs immediately and has a 10-second cron schedule. ```json { "SchedulerJobs": { "TestJob": { "RunImmediately": true, "CronSchedule": "0/10 * * * * *" } } } ``` -------------------------------- ### Add Job Dynamically Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Jobs can be added dynamically at runtime, for example, by retrieving options from a database context and then registering them with the scheduler. ```csharp var jobOptions = await _dbContext.JobOptions.FindAsync("TestJob"); _schedulerRegistration.AddOrUpdate(new TestJob(jobOptions, _loggerFactory.CreateLogger()), jobOptions); ``` -------------------------------- ### 3.x Job Implementation: TorahQuoteJob Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/Migration.md Example of a job class implementing `IScheduledJob` in version 3.x. Note the change in inheritance and how options are accessed using `Name`. ```csharp public class TorahQuoteJob : IScheduledJob { private readonly TorahQuoteJobOptions _options; private readonly TorahVerses _torahVerses; private readonly TorahService _service; /// /// Initializes a new instance of the class. /// /// /// /// public TorahQuoteJob( IOptionsMonitor options, TorahService service, TorahVerses torahVerses) { _options = options.Get(Name); _service = service ?? throw new ArgumentNullException(nameof(service)); _torahVerses = torahVerses ?? throw new ArgumentNullException(nameof(torahVerses)); } // job name and options name must match. public string Name { get; } = nameof(TorahQuoteJob); public async Task ExecuteAsync(CancellationToken cancellationToken) { var index = new Random().Next(_options.Verses.Length); var exp = _options.Verses[index]; _torahVerses.Current = await _service.GetVersesAsync(exp, cancellationToken); } } ``` -------------------------------- ### 2.x Job Implementation: TorahQuoteJob Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/Migration.md Example of a job class inheriting from `ScheduledJob` in version 2.x. This class defines a job that fetches and sets a Torah verse. ```csharp public class TorahQuoteJob : ScheduledJob { private readonly TorahQuoteJobOptions _options; private readonly TorahVerses _torahVerses; private readonly TorahService _service; /// /// Initializes a new instance of the class. /// /// /// /// public TorahQuoteJob( IOptionsMonitor options, TorahService service, TorahVerses torahVerses) : base(options.CurrentValue) { _options = options.CurrentValue; _service = service ?? throw new ArgumentNullException(nameof(service)); _torahVerses = torahVerses ?? throw new ArgumentNullException(nameof(torahVerses)); } public override async Task ExecuteAsync(CancellationToken cancellationToken) { var index = new Random().Next(_options.Verses.Length); var exp = _options.Verses[index]; _torahVerses.Current = await _service.GetVersesAsync(exp, cancellationToken); } } ``` -------------------------------- ### Define Cron Time Zone Property Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/CHANGELOG.md Example of a property declaration for CronTimeZone, likely used within a job or scheduler configuration. ```csharp public string CronTimeZone { get; }; ``` -------------------------------- ### Program.cs Configuration for CronScheduler Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Configures services for a .NET Core application, including adding the CronScheduler, registering jobs, and setting up HTTP clients and exception handling. This setup is typical for ASP.NET Core applications. ```csharp var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddScheduler(builder => { builder.Services.AddSingleton(); builder.Services .AddHttpClient() .AddTransientHttpErrorPolicy(p => p.RetryAsync()); builder.AddJob(); builder.Services.AddScoped(); builder.AddJob(); builder.AddUnobservedTaskExceptionHandler(sp => { var logger = sp.GetRequiredService().CreateLogger("CronJobs"); return (sender, args) => { logger?.LogError(args.Exception?.Message); args.SetObserved(); }; }); }); builder.Services.AddBackgroundQueuedService(applicationOnStopWaitForTasksToComplete: true); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddStartupJob(); builder.Services.AddStartupJob(); builder.Logging.AddConsole(); builder.Logging.AddDebug(); builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging")); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseRouting(); app.MapControllers(); app.MapDefaultControllerRoute(); app.MapRazorPages(); await app.RunStartupJobsAsync(); await app.RunAsync(); ``` -------------------------------- ### Basic Job Registration with AddJob Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/Migration.md Registering a job using the `AddJob()` method assumes the job name and options name are the same. This is the most straightforward registration method. ```csharp services.AddScheduler(ctx => { ctx.AddJob(); }); ``` -------------------------------- ### Enable Background Queued Service Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Add the background queued service to your application's services. This is typically done in the `Startup.cs` file. ```csharp services.AddBackgroundQueuedService(); ``` -------------------------------- ### Build and Run .NET Core Application Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerWorker/README.md Navigate to the project directory, build the solution, and run the CronSchedulerWorker application using the dotnet CLI. Scheduled jobs will execute according to their configuration. ```bash # Navigate to the project directory cd src/CronSchedulerWorker # Build the project dotnet build # Run the project dotnet run ``` -------------------------------- ### Add Scheduler with Custom Job Registration Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/CHANGELOG.md Configure the scheduler service, registering custom scheduled jobs and setting an unobserved task exception handler. Use TryAddSingleton for job registration to ensure only one instance is added if multiple attempts are made. ```csharp services.AddScheduler(builder => { // recommended to use TryAddSingleton builder.Services.TryAddSingleton(); builder.UnobservedTaskExceptionHandler = UnobservedHandler; }); ``` -------------------------------- ### Build and Run Cron Scheduler with dotnet CLI Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Commands to build and run the Cron Scheduler application using the .NET CLI. Jobs will execute based on their configured schedules. ```bash # Navigate to the project directory cd src/CronSchedulerApp # Build the project dotnet build # Run the project dotnet run ``` -------------------------------- ### Register Cron Job with Factory and Options Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Register a cron job using a factory method to provide custom options and dependencies. This is useful for complex configurations or when job and options names differ. ```csharp services.AddScheduler(ctx => { var jobName1 = "TestJob1"; ctx.AddJob( sp => { var options = sp.GetRequiredService>().Get(jobName1); return new TestJobDup(options, mockLoggerTestJob.Object); }, options => { options.CronSchedule = "*/5 * * * * *"; options.RunImmediately = true; }, jobName: jobName1); var jobName2 = "TestJob2"; ctx.AddJob( sp => { var options = sp.GetRequiredService>().Get(jobName2); return new TestJobDup(options, mockLoggerTestJob.Object); }, options => { options.CronSchedule = "*/5 * * * * *"; options.RunImmediately = true; }, jobName: jobName2); }); ``` -------------------------------- ### Define Scheduler Options Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Create a class inheriting from SchedulerOptions to define custom configurations for your scheduled job. ```csharp using CronScheduler.Extensions.Scheduler; public class MyScheduledJobOptions : SchedulerOptions { public string SomeOption { get; set; } = string.Empty; } ``` -------------------------------- ### Build Docker Image for Cron Scheduler Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Command to build the Docker image for the Cron Scheduler application. Ensure you are in the root directory of the project. ```bash docker build --pull --rm -f "src/CronSchedulerApp/Dockerfile" -t cronscheduler:latest . ``` -------------------------------- ### Register Job and Error Handler Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Register your custom job and its options with the scheduler in Program.cs or Startup.cs. Also, configure a custom handler for unobserved task exceptions. ```csharp services.AddScheduler(builder => { builder.AddJob(); }); // Add a custom error processing for internal errors builder.AddUnobservedTaskExceptionHandler(sp => { var logger = sp.GetRequiredService().CreateLogger("CronJobs"); return (sender, args) => { logger?.LogError(args.Exception?.Message); args.SetObserved(); }; }); ``` -------------------------------- ### Add Basic Job with CronScheduler Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Register a simple job using AddJob. Ensure the job name and options name match. ```csharp services.AddScheduler(ctx => { ctx.AddJob(); }); ``` -------------------------------- ### Singleton Schedule Job Implementation Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Defines a singleton scheduled job that retrieves and processes Torah verses based on configuration options. Ensure the job name matches the options name. ```csharp public class TorahQuoteJob : IScheduledJob { private readonly TorahQuoteJobOptions _options; private readonly TorahVerses _torahVerses; private readonly TorahService _service; /// /// Initializes a new instance of the class. /// /// /// /// public TorahQuoteJob( IOptionsMonitor options, TorahService service, TorahVerses torahVerses) { _options = options.Get(Name); _service = service ?? throw new ArgumentNullException(nameof(service)); _torahVerses = torahVerses ?? throw new ArgumentNullException(nameof(torahVerses)); } // job name and options name must match. public string Name { get; } = nameof(TorahQuoteJob); public async Task ExecuteAsync(CancellationToken cancellationToken) { var index = new Random().Next(_options.Verses.Length); var exp = _options.Verses[index]; _torahVerses.Current = await _service.GetVersesAsync(exp, cancellationToken); } } ``` -------------------------------- ### Configure Scheduler Jobs in appsettings.json Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Defines the structure for configuring scheduled jobs, including run options, API endpoints, and cron schedules. Use this to customize job behavior and timing. ```json { "SchedulerJobs": { "TorahQuoteJob": { "RunImmediately": true, "ApiUrl": "http://labs.bible.org/api/", "WebsiteUrl": "https://studybible.info/KJV_Strongs", "CronSchedule": "0/10 * * * * *", "Verses": [ "Genesis 1:1-3", "Exodus 3:14-15", "Isaiah 53", "Isaiah 26:18", "Proverbs 14:23", "Daniel 12:1-12" ] }, "UserJob": { "RunImmediately": true, "CronSchedule": "2 9 * * *", "ClaimName": "TestClaim" } } } ``` -------------------------------- ### Build Docker Image Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerWorker/README.md Build the Docker image for the CronSchedulerWorker application using the provided Dockerfile. This command ensures the latest base image is used. ```bash docker build --pull --rm -f "src/CronSchedulerWorker/Dockerfile" -t cronschedulerworker:latest . ``` -------------------------------- ### Complex Factory Job Registration Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/Migration.md Registering jobs using a factory allows for custom dependency injection and configuration of job options. This is useful for jobs requiring specific configurations or multiple instances with different settings. ```csharp services.AddScheduler(ctx => { var jobName1 = "TestJob1"; ctx.AddJob( sp => { var options = sp.GetRequiredService>().Get(jobName1); return new TestJobDup(options, mockLoggerTestJob.Object); }, options => { options.CronSchedule = "*/5 * * * * *"; options.RunImmediately = true; }, jobName: jobName1); var jobName2 = "TestJob2"; ctx.AddJob( sp => { var options = sp.GetRequiredService>().Get(jobName2); return new TestJobDup(options, mockLoggerTestJob.Object); }, options => { options.CronSchedule = "*/5 * * * * *"; options.RunImmediately = true; }, jobName: jobName2); }); ``` -------------------------------- ### Queue Background Work Item Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/README.md Inject `IBackgroundTaskQueue` into your service to queue background work items. The work item is an asynchronous lambda function that accepts a cancellation token. ```csharp public class MyService { private readonly IBackgroundTaskQueue _taskQueue; public MyService(IBackgroundTaskQueue taskQueue) { _taskQueue = taskQueue; } public void RunTask() { _taskQueue.QueueBackgroundWorkItem(async (token)=> { // run some task await Task.Delay(TimeSpan.FromSeconds(10), token); }); } } ``` -------------------------------- ### Implement IScheduledJob Interface Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Implement this interface for your custom scheduled job. Ensure the constructor accepts necessary dependencies like ILogger. ```csharp using System; using System.Threading; using System.Threading.Tasks; using CronScheduler.Extensions.Scheduler; using Microsoft.Extensions.Logging; public class MyScheduledJob : IScheduledJob { private readonly ILogger _logger; public MyScheduledJob(ILogger 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; } } ``` -------------------------------- ### Run Cron Scheduler Docker Container Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerApp/README.md Command to run the Cron Scheduler application as a detached Docker container. Ports 443 and 80 are exposed. ```bash docker run --rm -d -p 443:443/tcp -p 8080:80/tcp cronscheduler:latest ``` -------------------------------- ### 3.x IScheduledJob Interface Definition Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/Migration.md The `IScheduledJob` interface in version 3.x requires the `Name` property and the `ExecuteAsync` method. Properties like `CronSchedule`, `CronTimeZone`, and `RunImmediately` are removed. ```csharp /// /// Forces the implementation of the required methods for the job. /// public interface IScheduledJob { /// /// The name of the executing job. /// In order for the options to work correctly make sure that the name is matched /// between the job and the named job options. /// string Name { get; } /// /// Job that will be executing on this schedule. /// /// /// Task ExecuteAsync(CancellationToken cancellationToken); } ``` -------------------------------- ### Run Docker Container Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/src/CronSchedulerWorker/README.md Run the CronSchedulerWorker application as a detached Docker container. The '--rm' flag ensures the container is removed upon exit. ```bash docker run --rm -d cronschedulerworker:latest ``` -------------------------------- ### Handle Unobserved Task Exceptions in Cron Jobs Source: https://github.com/kdcllc/cronscheduler.aspnetcore/blob/master/CHANGELOG.md Register a custom exception handler for unobserved tasks within the CRON job scheduler. This allows for centralized logging and management of exceptions that are not caught by the application's normal error handling. ```csharp builder.AddUnobservedTaskExceptionHandler(sp => { var logger = sp.GetRequiredService().CreateLogger("CronJobs"); return (sender, args) => { logger?.LogError(args.Exception?.Message); args.SetObserved(); }; }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.