All Projects โ†’ kdcllc โ†’ Cronscheduler.aspnetcore

kdcllc / Cronscheduler.aspnetcore

Licence: mit
Cron Scheduler for AspNetCore 2.x/3.x or DotNetCore 2.x/3.x Self-hosted

Projects that are alternatives of or similar to Cronscheduler.aspnetcore

Awesome Microservices Netcore
๐Ÿ’Ž A collection of awesome training series, articles, videos, books, courses, sample projects, and tools for Microservices in .NET Core
Stars: โœญ 865 (+765%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core, dotnet-core, dotnetcore
Quartznet
Quartz Enterprise Scheduler .NET
Stars: โœญ 4,825 (+4725%)
Mutual labels:  scheduler, cron, scheduling, scheduled-jobs, dotnetcore
Practical Aspnetcore
Practical samples of ASP.NET Core 2.1, 2.2, 3.1, 5.0 and 6.0 projects you can use. Readme contains explanations on all projects.
Stars: โœญ 6,199 (+6099%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core, dotnet-core
Aspnetcore Developer Roadmap
Roadmap to becoming an ASP.NET Core developer in 2021
Stars: โœญ 8,248 (+8148%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core, aspnet-core
Docker Series
Docker Series about containerizing ASP.NET Core app with MySQL..
Stars: โœญ 88 (-12%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core, dotnetcore
Architecture
.NET 6, ASP.NET Core 6, Entity Framework Core 6, C# 10, Angular 13, Clean Code, SOLID, DDD.
Stars: โœญ 2,285 (+2185%)
Mutual labels:  aspnetcore, aspnet-core, dotnet-core, dotnetcore
awesome-dotnet-async
A curated list of awesome articles and resources to learning and practicing about async, threading, and channels in .Net platform. ๐Ÿ˜‰
Stars: โœญ 84 (-16%)
Mutual labels:  aspnetcore, dotnetcore, aspnet-core, asp-net-core
King.Service
Task scheduling for .NET
Stars: โœญ 34 (-66%)
Mutual labels:  dotnetcore, scheduler, scheduling, task-scheduler
Awesome-Nuget-Packages
๐Ÿ“ฆ A collection of awesome and top .NET packages sorted by most popular needs.
Stars: โœญ 87 (-13%)
Mutual labels:  aspnetcore, dotnetcore, aspnet-core, asp-net-core
ChatService
ChatService (SignalR).
Stars: โœญ 26 (-74%)
Mutual labels:  aspnetcore, dotnetcore, aspnet-core, asp-net-core
Simplcommerce
A simple, cross platform, modularized ecommerce system built on .NET Core
Stars: โœญ 3,474 (+3374%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core, dotnetcore
Equinoxproject
Full ASP.NET Core 5 application with DDD, CQRS and Event Sourcing concepts
Stars: โœญ 5,120 (+5020%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core
Aspnetcore Practice
ASP.NET Core ๅฐˆๆกˆ็ทด็ฟ’้›†ๅˆ๏ผŒASP.NET Core Practice Projects
Stars: โœญ 80 (-20%)
Mutual labels:  aspnet-core, dotnet-core, dotnetcore
Awesome Blazor
Resources for Blazor, a .NET web framework using C#/Razor and HTML that runs in the browser with WebAssembly.
Stars: โœญ 6,063 (+5963%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core
Asp.net Core Template
A ready-to-use template for ASP.NET Core with repositories, services, models mapping, DI and StyleCop warnings fixed.
Stars: โœญ 599 (+499%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core
Aspnetboilerplate
ASP.NET Boilerplate - Web Application Framework
Stars: โœญ 10,061 (+9961%)
Mutual labels:  aspnetcore, aspnet-core, dotnet-core
Netcorebbs
ASP.NET Core Light forum NETCoreBBS
Stars: โœญ 483 (+383%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core
Nopcommerce
The most popular open-source eCommerce shopping cart solution based on ASP.NET Core
Stars: โœญ 6,827 (+6727%)
Mutual labels:  asp-net-core, aspnetcore, dotnet-core
Ocelot
.NET core API Gateway
Stars: โœญ 6,675 (+6575%)
Mutual labels:  asp-net-core, dotnet-core, dotnetcore
Znetcs.aspnetcore.authentication.basic
A simple basic authentication middleware.
Stars: โœญ 40 (-60%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core

CronScheduler.AspNetCore

Build status NuGet Nuget feedz.io

Note: Pre-release packages are distributed via feedz.io.

Summary

The goal of this library was to design a simple Cron Scheduling engine that could be used with DotNetCore IHost or with AspNetCore IWebHost.

It is much lighter than Quartz schedular or its alternatives. In the heart of its design was KISS principle.

The CronScheduler can operate inside of any .NET Core GenericHost IHost thus makes it simpler to setup and configure but it always allow to be run inside of Kubernetes.

In addition IStartupJob was added to support async initialization of critical process before the IHost is ready to start.

Please refer to Migration Guide for the upgrade.

  • Install package for AspNetCore hosting .NET CLI
    dotnet add package CronScheduler.AspNetCore
  • Install package for IHost hosting .NET CLI
    dotnet add package CronScheduler.Extensions

Uses Crontab format for Jobs/Tasks schedules

This library supports up to 5 seconds job intervals in the Crontab format thank to HangfireIO/Cronos library.

You can use https://crontab-generator.org/ to generated needed job/task schedule.

Cron expression is a mask to define fixed times, dates and intervals. The mask consists of second (optional), minute, hour, day-of-month, month and day-of-week fields. All of the fields allow you to specify multiple values, and any given date/time will satisfy the specified Cron expression, if all the fields contain a matching value.

                                       Allowed values    Allowed special characters   Comment

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ second (optional)       0-59              * , - /                      
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ minute                0-59              * , - /                      
โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ hour                0-23              * , - /                      
โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ day of month      1-31              * , - / L W ?                
โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ month           1-12 or JAN-DEC   * , - /                      
โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ day of week   0-6  or SUN-SAT   * , - / # L ?                Both 0 and 7 means SUN
โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
* * * * * *

buymeacoffee

Give a Star! โญ๏ธ

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

Demo Applications

  • CronSchedulerWorker - this example demonstrates how to use CronScheduler with new Microsoft .NET Core Workers Template
  • CronSchedulerApp - this example demonstrates how to use CronScheduler with AspNetCore applications.

There are two ways that options and jobs can be registered within the Scheduler Jobs.

  1. The basic and most effective way to register is via IConfiguration

This job registration is assuming that the name of the job and options name are the same.

    services.AddScheduler(ctx =>
    {
        ctx.AddJob<TestJob>();
    });
  1. The complex factory registration of the same cron job with different options
        services.AddScheduler(ctx =>
        {
            var jobName1 = "TestJob1";

            ctx.AddJob(
                sp =>
                {
                    var options = sp.GetRequiredService<IOptionsMonitor<SchedulerOptions>>().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<IOptionsMonitor<SchedulerOptions>>().Get(jobName2);
                    return new TestJobDup(options, mockLoggerTestJob.Object);
                }, options =>
                {
                    options.CronSchedule = "*/5 * * * * *";
                    options.RunImmediately = true;
                },
                jobName: jobName2);
        });

Sample code for Singleton Schedule Job and its dependencies

    public class TorahQuoteJob : IScheduledJob
    {
        private readonly TorahQuoteJobOptions _options;
        private readonly TorahVerses _torahVerses;
        private readonly TorahService _service;

        /// <summary>
        /// Initializes a new instance of the <see cref="TorahQuoteJob"/> class.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="service"></param>
        /// <param name="torahVerses"></param>
        public TorahQuoteJob(
            IOptionsMonitor<TorahQuoteJobOptions> 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);
        }
    }

Then register this service within the Startup.cs The sample uses Microsoft.Extensions.Http.Polly extension library to make http calls every 10 seconds.

    services.AddScheduler(builder =>
    {
        builder.Services.AddSingleton<TorahVerses>();

        // Build a policy that will handle exceptions, 408s, and 500s from the remote server
        builder.Services.AddHttpClient<TorahService>()
            .AddTransientHttpErrorPolicy(p => p.RetryAsync());
        builder.AddJob<TorahQuoteJob, TorahQuoteJobOptions>();

        builder.UnobservedTaskExceptionHandler = UnobservedHandler;
    });

Sample code for Scoped or Transient Schedule Job and its dependencies

    public class UserJob : IScheduledJob
    {
        private readonly UserJobOptions _options;
        private readonly IServiceProvider _provider;

        public UserJob(
            IServiceProvider provider,
            IOptionsMonitor<UserJobOptions> options)
        {
            _options = options.Get(Name);
            _provider = provider ?? throw new ArgumentNullException(nameof(provider));
        }

        public string Name { get; } = nameof(UserJob);

        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task
            using var scope = _provider.CreateScope();
            var userService = scope.ServiceProvider.GetRequiredService<UserService>();

            var users = userService.GetUsers();

            foreach (var user in users)
            {
                await userService.AddClaimAsync(user, new Claim(_options.ClaimName, DateTime.UtcNow.ToString()));
            }
        }
    }

Then register this service within the Startup.cs

        services.AddScheduler(builder =>
        {
            builder.Services.AddScoped<UserService>();
            builder.AddJob<UserJob, UserJobOptions>();

            builder.UnobservedTaskExceptionHandler = UnobservedHandler;
        });

IStartupJobs to assist with async jobs initialization before the application starts

There are many case scenarios to use StartupJobs for the IWebHost interface or IGenericHost. Most common case scenario is to make sure that database is created and updated. This library makes it possible by simply doing the following:

  • In the Program.cs file add the following:
        public static async Task Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            // process any async jobs required to get the site up and running
            await host.RunStartupJobsAync();

            host.Run();
        }
  • Register the startup job in Program.cs or in Startup.cs file.
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddStartupJob<SeedDatabaseJob>();
            })
            .ConfigureLogging((context, logger) =>
            {
                logger.AddConsole();
                logger.AddDebug();
                logger.AddConfiguration(context.Configuration.GetSection("Logging"));
            })
            .UseStartup<Startup>();
}

Background Queues

In some instances of the application the need for queuing of the tasks is required. In order to enable this add the following in Startup.cs.

    services.AddBackgroundQueuedService();

Then add sample async task to be executed by the Queued Hosted Service.

    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);
            }});
        }
    }

Docker build

Utilizes King David Consulting LLC DotNet Docker Image

    docker-compose -f "docker-compose.yml" -f "docker-compose.override.yml" up -d --build

Note

Workaround for Retrying 'FindPackagesByIdAsync' for source in Docker containers restore.

 dotnet restore --disable-parallel

License

MIT License Copyright (c) 2017 King David Consulting LLC

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].