Quartz.NET scheduler
- Create class library project which will contains all needed Quartz jobs.
- Install package
Scheduler.Quartz
. - Create your custom Quartz jobs (for example,
ExampleJob
). - Inherit this job:
- from abstract class
LoggableJob
orLoggableJobAsync
fromScheduler.Quartz.Abstract
namespace; - or just from
IJob
interface ofQuartz
namespace.
- from abstract class
- Implement logic of job.
- Install appropriate IOC-container - all possible IOC-container are listed here
- Install packages:
Scheduler.Quartz
Scheduler.Quartz.Ioc.ServiceProvider
Quartz.Plugings
- only if your Quartz configured from *.xml file ("file configured scheduler")
- In your
Startup
class add the Quartz scheduler:public void ConfigureServices(IServiceCollection services) { // ... services.AddQuartz(new QuartzSchedulerOptions() { ConfigSource = ConfigSource.File, // Or // ConfigSource = ConfigSource.InMemory, // For in memory configured Quartz scheduler specify type of implementation of ISchedulerRunnerFactory: // InMemorySchedulerFactoryType = typeof(MemorySchedulerFactory), // Specify type of your 1 custom Qartz job for automatically // registering all jobs from type's assembly. // Otherwise you need register your custom jobs manually. OneOfCustomQuartzJobsType = typeof(ExampleLogJob) }); }
- Create implementation of
IHostedService
(read more about hosted services on MS docs) and inject theISchedulerRunnerFactory
to constructor - for example:public class QuartzSchedulerHostedService : IHostedService { private readonly IScheduleRunner _scheduler; public QuartzSchedulerHostedService(ISchedulerRunnerFactory schedulerRunnerFactory) { _scheduler = schedulerRunnerFactory.Create(); } public async Task StartAsync(CancellationToken cancellationToken) { // You can configure Quartz memory-jobs here: // await _scheduler.ScheduleRepeatableJob<ExampleLogJobAsync>(60); await _scheduler.Start(); } public Task StopAsync(CancellationToken cancellationToken) { return _scheduler.Stop(); } }
- Configure this hosted service in your
GenericHost
(orWebHost
) inProgram.cs
:public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() // some configurations of .NET Core Host .ConfigureServices((context, services) => { services.AddSingleton<IHostedService, QuartzSchedulerHostedService>(); }) // some other configurations ;
- That is all - when the .NET Core host will be start then all implementations of
IHostedService
will be start too.
P.S. For configuring Quartz via config files you may need next files:
quartz.config
with settings of Quartz scheduler;*.xml
file with jobs settings - you can seequartz_example.config
andquartz_jobs_example.xml
.
See inside examples folder.