Job Scheduler for .NET applications with Quartz.Net

Creating a Job Scheduler for .NET application

Sometimes we need to create Job scheduler for our .NET applications. For an example we might need to send automated emails to end users based on some conditions. This task is bit challenging but don’t worry. We have some full featured Nuget packages we can use for this task.

I’m going to use Quartz.Net Enterprise Scheduler .NET package for this tutorial and show you how to create a job scheduler for .NET applications. The version I’m using for this is Quartz 2.6.2. I have created a MVC web application for this tutorial. So we are going to implement a job scheduler for our web application.

First go to nuget package manager and install the package Quartz (by Marko Lahma).

Then We need to create the TaskScheduler class.

public static class TaskSchedular
    {
        public static void Start()
        {
            try
            {
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };

                // Grab the Scheduler instance from the Factory
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // and start it off
                scheduler.Start();

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create<EmailReminder>()

                    .WithIdentity("EmailReminder", "Reminders")

                    .Build();


                // Trigger the job to run now, and then repeat every 10 seconds
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "Reminders")
                    .StartAt(new DateTimeOffset(2019,06,19,00,30,00,DateTimeOffset.Now.Offset)) // Start at 2019/06/19 : 12.30 AM and run every 24 hours
                    .WithSimpleSchedule(x => x
                        .WithIntervalInHours(24)
                        .RepeatForever())
                    .Build();

                // Tell quartz to schedule the job using our trigger
                scheduler.ScheduleJob(job, trigger);

                // and last shut down the scheduler when you are ready to close your program
                //scheduler.Shutdown();

            }
            catch (SchedulerException se)
            {
                LogWriter.LogActivity(se.Message, se.StackTrace, "FAILED");  // Write error logs
            }
        }
}

StartAt(new DateTimeOffset(2019,06,19,00,30,00,DateTimeOffset.Now.Offset))

This will make the task to start on 2019/06/19 12.30 AM and run every 24 Hrs. Rather than hard coding the values we can use web config to keep this values if we want to change the values in future.

Then create the job class implementing the IJob interface from Quartz. This class is the job class and we can implement our email sending logic here.

public class EmailReminder: IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            try
            {
               // Implement your business logic to send emails
            }
            catch (Exception ex)
            {
               LogWriter.LogActivity(ex.Message, ex.StackTrace, "Fialed"); // Write error logs
            }
        }

Then register the TaskScheduler in Global.asax file as below. By registering this inside Global.asax file we are setting our job scheduler to start when the application starts. But still the task will start at the time we set in Job class.

protected void Application_Start()     {

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            UnityConfig.RegisterComponents();

            TaskSchedular.Start();

        }

Sajith Dilhan on Linkedin
Sajith Dilhan
Software Developer at Sana Commerce

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.