• Stars
    star
    14
  • Rank 1,438,076 (Top 29 %)
  • Language
    C#
  • Created over 2 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

NCrontab.Scheduler is a simple, open source task scheduling system that can be used in any .NET application

NCrontab.Scheduler

Version Downloads

NCrontab.Scheduler is a simple, open source task scheduling system that can be used in any .NET application. The main component of this project is a thread-safe scheduler which facilitates very basic scheduling operations like adding, remove or changing task schedules. NCrontab.Scheduler is built on top of NCrontab.

Download and Install NCrontab.Scheduler

This library is available on NuGet: https://www.nuget.org/packages/NCrontab.Scheduler Use the following command to install NCrontab.Scheduler using NuGet package manager console:

PM> Install-Package NCrontab.Scheduler

You can use this library in any .NET Standard or .NET Core project.

ASP.NET Core Integration

In ASP.NET Core projects, use following NuGet package: https://www.nuget.org/packages/NCrontab.Scheduler.AspNetCore Use the following command to install NCrontab.Scheduler.AspNetCore using NuGet package manager console:

PM> Install-Package NCrontab.Scheduler.AspNetCore

You can use this library in any ASP.NET Core project which is compatible to .NET Core 3.1 and higher.

API Usage

Creating a Scheduler

Scheduler implements the main scheduler operations.

Create new Scheduler instance

You can either create a new instance of Scheduler manually:

IScheduler scheduler = new Scheduler();

Access static Scheduler instance

Alternatively, you can access the provided singleton instance Scheduler.Current.

Inject Scheduler using dependency injection

Alternatively, you can register/resolve IScheduler in Microsoft's DI framework Microsoft.Extensions.DependencyInjection.

serviceCollection.AddScheduler();

This AddScheduler call regist ers IScheduler and ISchedulerFactory as singleton services which can now be injected in your code. If you prefer to have multiple instances of IScheduler across your code, inject ISchedulerFactory instead and use the Create method to create new instances of IScheduler.

Scheduler Options

The Scheduler class has an extra parameter ISchedulerOptions which allows to override the default configuration of the scheduler. If you use dependency injection, you can also configure the scheduler using the AddScheduler method:

serviceCollection.AddScheduler(o =>
{
    o.DateTimeKind = DateTimeKind.Utc;
});

Scheduler options can also be read from appSettings.json. Create a new section in your appSettings.json.

"NCrontab.Scheduler": {
    "DateTimeKind": "Utc"
},

Refer to the new configuration section when you call AddScheduler:

var configurationSection = builder.Configuration.GetSection("NCrontab.Scheduler");
builder.Services.AddScheduler(configurationSection);

Following options are available:

  • DateTimeKind: Interprets the given cron expressions as UTC or local time. Default is UTC.

Add Scheduled Tasks

Use method AddTask with all the provided convenience overloads to add tasks to the scheduler. A task is composed of a cron pattern which specifies the recurrance interval and an action (for synchronous callbacks) or a task (for asynchronous callbacks).

Tasks can be added to the scheduler either before or after the scheduler has been started.

scheduler.AddTask(
    cronExpression: CrontabSchedule.Parse("* * * * *"),
    action: ct => { Console.WriteLine($"{DateTime.Now:O} -> Task runs every minutes"); });

scheduler.AddTask(
    cronExpression: CrontabSchedule.Parse("*/2 * * * *"),
    action: ct => { Console.WriteLine($"{DateTime.Now:O} -> Task runs every second minute"); });

scheduler.AddTask(
    cronExpression: CrontabSchedule.Parse("0 * * * *"),
    action: ct => { Console.WriteLine($"{DateTime.Now:O} -> Task runs every hour"); });
            
scheduler.AddTask(
    cronExpression: CrontabSchedule.Parse("0 0 * * *"),
    action: ct => { Console.WriteLine($"{DateTime.Now:O} -> Task runs every day at midnight"); });
            
scheduler.AddTask(
    cronExpression: CrontabSchedule.Parse("0 0 1 1 *"),
    action: ct => { Console.WriteLine($"{DateTime.Now:O} -> Task runs on Januar 1 every year"); });    

A very helpful resource for creating cron expression is https://crontab.guru.

Starting and Stopping

Use method IScheduler.StartAsync to start the scheduler operations. This method can be awaited which blocks all further calls until all scheduled tasks have been canceled or removed. Use IScheduler.Start if you prefer to start the scheduler without blocking the current execution path of your program. If the scheduler is started without having added any tasks, it just waits (and blocks) until tasks are added.

Scheduled tasks can be added at runtime. If the scheduler is started without having added tasks beforehand, it logs this info: Scheduler is waiting for tasks. Use AddTask methods to add tasks.

IScheduler.Stop attempts to cancel all scheduled tasks immediately.

About Scheduling

Real-time systems are systems that are required to respond to an external event in some timely manner. "Timely manner" is often misinterpreted as "very fast". However, for many applications this just means the system needs to react in a specific time. It can be seconds, minutes, hours or even years. Schedulers such as NCrontab.Scheduler can help to satisfy such timing constraints.

Scheduler Algorithm

NCrontab.Scheduler is a classic implementation of the Earliest Deadline First (EDF) algorithm. The EDF algorithm will always schedule the task(s) whose deadline is soonest.

The scheduler provides a dynamic prioritization of tasks by evaluating the cron expressions of the tasks. Each scheduling iteration attempts to find the task with the earliest possible execution date/time.

If tasks are added or removed while waiting for the next execution, the earliest possible execution date/time is re-evaluated.

Task Overrun Condition

Task overrun conditions can happen if a scheduled task's execution time exceeds the limit of one minute. Task overrun can lead to situations where other tasks miss their projected next execution time. Consequently, each of other tasks start missing their deadlines one after the other in sequence (domino effect). This is a classic EDF scheduling problem and can lead to dangerous situations!

Thread-Safety

All scheduler operations are kept thread-safe. Adding and removing tasks as well as starting and stopping the scheduler can be done concurrently.

Task Isolation

Each task run is isolated from all other scheduled tasks. The success or failure of execution does not have any negative side effect on other scheduled tasks.

License

This project is Copyright © 2023 Thomas Galliker. Free for non-commercial use. For commercial use please contact the author.

Links

More Repositories

1

ObjectDumper

ObjectDumper is a utility which aims to serialize C# objects to string for debugging and logging purposes.
C#
395
star
2

ValueConverters.NET

A collection of commonly used IValueConverters for .NET applications
C#
147
star
3

Diacritics.NET

Finds and replaces diacritics in strings
C#
72
star
4

EntityFramework.Toolkit

EntityFramework best practices, patterns, utilities and extensions
C#
67
star
5

Plugin.FirebasePushNotifications

Receive and handle firebase push notifications in .NET MAUI apps
C#
60
star
6

CameraScanner.Maui

Camera preview and barcode scanner for .NET MAUI apps
C#
24
star
7

HttpClient.Caching

Caching Extension for .NET HttpClient
C#
21
star
8

PushNotifications.Server

Server-side .NET SDK for Apple APNS and and Google FCM
C#
20
star
9

EmployeeManagement

Multi-layer demo application
C#
18
star
10

EnumUtils

Commonly used .NET Enum utilities
C#
16
star
11

TypeConverter

TypeConverter is a lightweight, portable class library which allows to convert between objects of different types.
C#
12
star
12

ObservableView

Collections overlay for searching, filtering, sorting and grouping
C#
12
star
13

HighlightMarker

A simple-to-use highlight marker for search text highlighting
C#
11
star
14

XmlSerializerHelper

Serializes and deserializes any .Net object from/to XML
C#
11
star
15

Plugin.SegmentedControl.Maui

Segmented control for .NET MAUI apps
C#
10
star
16

EFCore.Toolkit

EntityFrameworkCore best practices, patterns, utilities and extensions
C#
9
star
17

Guards

Protects your public APIs
C#
9
star
18

CrossPlatformLibrary

An extensible cross-platform toolkit which provides a basic set of functionality used in most mobile apps.
C#
9
star
19

CrossPlatformLibrary.WebBrowser

CrossPlatformLibrary.WebBrowser is a cross-platform abstraction which allows to open browser requests
C#
5
star
20

ResourceLoader

A utility for reading embedded resources from assemblies
C#
5
star
21

CrossPlatformLibrary.Geolocation

C#
5
star
22

Paging.NET

Paging.NET is a basic toolkit which provides incremential server-side data loads.
C#
4
star
23

Tracing.NET

An extensible logging/tracing framework for all major .Net platforms.
C#
4
star
24

NuGetUtils

A command-line utility to delete/unlist NuGet packages
C#
4
star
25

PiWeatherStation

Weather Station for RasperryPi and Waveshare ePaper Displays
C#
3
star
26

MauiPopups

C#
3
star
27

CrossPlatformLibrary.Settings

C#
2
star
28

NLog.Targets.AppCenter

NLog targets for Microsoft.AppCenter
C#
1
star
29

RaspberryPi.NET

C#
1
star
30

OpenWeatherMap.API

OpenWeatherMap API client for .NET
C#
1
star
31

MeteoSwissApi

.NET API for Swiss national weather provider MeteoSwiss
C#
1
star
32

MauiMocks

Library for running Microsoft.Maui inside of unit tests
C#
1
star