Most of the applications in our internet world are having some automatic task scheduling mechanism like email reminders, expiry notifications etc. For small-scale applications, we can do this type of functionality by running background tasks. Quartz.net is one of the famous libraries to schedule background tasks in .net web applications.
I am going to explain here steps to set up Quartz scheduler and schedule job in ASP.NET Core web application with Quartz 3.0 and inject dependency to Quartz job using the Ninject library.
1) Install Quartz, Ninject and Ninject.Web.Common NuGet packages in your target application using NuGet package manager.
2) Now inherit SimpleJobFactory class and implement NewJob method to inject dependency to the job like shown in below image.
Here, (Ijob)this._kernel.Get(bundle.JobDetail.JobType) is used to inject required dependency on the job that we can see in the next steps.
3) Now, write the service for the task you want to schedule using Quartz like shown in below snippet.
Here, I have written email sending cron service and injected emailBuilder dependency here. You can write your task code in the scheduler method or call multiple methods inside this method and inject respective dependencies.
4) Now I will create the job for this service by implementing IJob interface like shown in below image.
5) Now schedule this job and also inject dependency through the Ninject kernel, so that we can get emailBuilder dependency inside this service when it is called.
-Initialize Ninject kernel and inject dependency:
Full code of initializing kernel method called and get scheduler dependency and schedule jobs with cron schedule like shown below:
6) Now you can call this method inside Startup.cs file as a middleware with app.UseQuartz() inside Configure() method.
Your Quartz job is scheduled and ready to run now, you can schedule it as per your requirement and use it in your application.