Here, we will learn about using Quartz scheduler in ASP.NET MVC. The scheduler is very useful for running task in the backgrounds. For example, we have to send an email every 1 hour, so the simplest method will be to create a scheduler for email sending task so that it can be called at every 1 hour.

Prerequisites:

  • Basic knowledge of ASP.NET MVC

Create a new project in ASP.NET MVC.

Open the Package Manager Console and type the following command in it.

Install-Package Quartz -Version 3.0.7

In the Models folder, create a class as ExecuteTaskServiceCallJob.cs

using Quartz;
using System;
using System.Configuration;
using System.Threading.Tasks;

namespace QuartzSchedularDemo.Models
{
    public class ExecuteTaskServiceCallJob : IJob
    {
        public static readonly string SchedulingStatus = ConfigurationManager.AppSettings["ExecuteTaskServiceCallSchedulingStatus"];
        public Task Execute(IJobExecutionContext context)
        {
            var task = Task.Run(() =>
            {
                if (SchedulingStatus.Equals("ON"))
                {
                    try
                    {
                        //Do whatever stuff you want
                    }
                    catch (Exception ex)
                    {

                    }

                }

            });

            return task;
        }
    }
}

Create another class as ExecuteTaskServiceCallScheduler.cs file

using Quartz;
using Quartz.Impl;
using System;
using System.Configuration;

namespace QuartzSchedularDemo.Models
{
    public class ExecuteTaskServiceCallScheduler
    {
        private static readonly string ScheduleCronExpression = ConfigurationManager.AppSettings["ExecuteTaskScheduleCronExpression"];

        public static async System.Threading.Tasks.Task StartAsync()
        {
            try
            {
                var scheduler = await StdSchedulerFactory.GetDefaultScheduler();

                if (!scheduler.IsStarted)
                {
                    await scheduler.Start();
                }

                var job = JobBuilder.Create<ExecuteTaskServiceCallJob>()
                    .WithIdentity("ExecuteTaskServiceCallJob1", "group1")
                    .Build();

                var trigger = TriggerBuilder.Create()
                    .WithIdentity("ExecuteTaskServiceCallTrigger1", "group1")
                    .WithCronSchedule(ScheduleCronExpression)
                    .Build();

                await scheduler.ScheduleJob(job, trigger);
            }
            catch (Exception ex)
            {
                
            }
        }
    }
}

Open the Web config file present at the root folder and add two keys in it.

<add key="ExecuteTaskServiceCallSchedulingStatus" value="ON" />
<add key="ExecuteTaskScheduleCronExpression" value="0 0/1 * 1/1 * ? *" />

Finally, open the Global.asax.cs file and add the reference for schedular there.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ExecuteTaskServiceCallScheduler.StartAsync().GetAwaiter().GetResult();
        }

That’s it. This corn expression ( 0 0/1 * 1/1 * ? * ) will make a call at every one minute to the¬†ExecuteTaskServiceCallJob.cs¬†file.

using-quartz-schedular-in-asp-net-mvc-1

As you can see the debugger has come after one minute. You can put your own code in the try block.