A Job Scheduler sitting on top of `IHostedService` in dotnet. Often times one finds themself between the simplicisty of the `BackgroundService`/`IHostedService` and the complexity of a full blown `Hangfire` or `Quartz` scheduler. This library aims to fill that gap by providing a simple and easy to use job scheduler that can be used in any dotnet application and feels "native".
$ dotnet add package NCronJobThe library moved from LinkDotNet.NCronJob to just NCronJob!
Please uninstall the old package and install the new one.
A Job Scheduler sitting on top of IHostedService in dotnet.
Often times one finds themself between the simplicity of the BackgroundService/IHostedService and the complexity of
a full-blown Hangfire or Quartz scheduler.
This library aims to fill that gap by providing a simple and easy to use job scheduler that can be used in any dotnet
application and feels "native".
So no need for setting up a database, just schedule your stuff right away! The library gives you two ways of scheduling jobs:
The whole documentation can be found here: NCronJob Documentation
As this is a simple scheduler, some features are not included by design. If you need these features, you might want to
look into a more advanced scheduler like Hangfire or Quartz.
There are two ways of defining a job.
You can use this library in a simple one-liner:
builder.Services.AddNCronJob((ILoggerFactory factory, TimeProvider timeProvider) =>
{
var logger = factory.CreateLogger("My Anonymous Job");
logger.LogInformation("Hello World - The current date and time is {Time}", timeProvider.GetLocalNow());
}, "*/5 * * * * *");
With this simple lambda, you can define a job that runs every 5 seconds. Pass in all dependencies, just like you would with a Minimal API.
IJob interfaceusing NCronJob;
public class PrintHelloWorld : IJob
{
private readonly ILogger<PrintHelloWorld> logger;
public PrintHelloWorld(ILogger<PrintHelloWorld> logger)
{
this.logger = logger;
}
public Task RunAsync(JobExecutionContext context, CancellationToken token)
{
logger.LogInformation("Hello World");
logger.LogInformation("Parameter: {Parameter}", context.Parameter);
return Task.CompletedTask;
}
}
Program.csbuilder.Services.AddNCronJob(options =>
options.AddJob<PrintHelloWorld>(j =>
{
// Every minute and optional parameter
j.WithCronExpression("* * * * *")
.WithParameter("Hello World");
}));
If the need arises and you want to trigger a job instantly, you can do so:
public class MyService
{
private readonly IInstantJobRegistry jobRegistry;
public MyService(IInstantJobRegistry jobRegistry) => this.jobRegistry = jobRegistry;
public void MyMethod() => jobRegistry.RunInstantJob<MyJob>("I am an optional parameter");
}
Thanks to all contributors and people that are creating bug-reports and valuable input: