How to Use Quartz Scheduler in ASP.NET Core – Windows ASP.NET Core Hosting 2020 | Review and Comparison

In this tutorial, we will learn how to use the Quartz scheduler in ASP.NET Core. We may perform jobs in the background using this scheduler. We can use Quartz scheduling to perform a job every 5 minutes.

Step 1

To begin, make a project with the ASP.NET core web application template. Choose Asp.net MVC for your online application.

Step 2

There are two ways to install the Quartz package.

Search for Quartz in the Nuget package manager and install it.

Using NuGet package manager console.

Step 3

Now we’ll make a folder under the models and call it anything we want. We’ll make a task and a scheduler in this folder.

Create Task

The objective is to create a basic class where you can write your logic.

We’ll add a task in the schedule folder and call it task1. We shall save the current time in a text file in this task.

The class code is shown below,

using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace QuartzSchduling.Models.Schedule {
    public class Task1: IJob {
        public Task Execute(IJobExecutionContext context) {
            var task = Task.Run(() => logfile(DateTime.Now));;
            return task;
        }
        public void logfile(DateTime time) {
            string path = "C:\log\sample.txt";
            using(StreamWriter writer = new StreamWriter(path, true)) {
                writer.WriteLine(time);
                writer.Close();
            }
        }
    }
}

Now, beneath the c drive, make a folder and call it to log. In this folder, we’ll make a text file with the name sample.txt.

Scheduler task

We’ll now construct a new class that will handle the trigger task. This class’s job is to start the task that I’ve already established. Set the frequency at which it runs.

Below is the code of the class,

using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QuartzSchduling.Models.Schedule {
    public class SchedulerTask {
        private static readonly string ScheduleCronExpression = "* * * ? * *";
        public static async System.Threading.Tasks.Task StartAsync() {
            try {
                var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
                if (!scheduler.IsStarted) {
                    await scheduler.Start();
                }
                var job1 = JobBuilder.Create < Task1 > ().WithIdentity("ExecuteTaskServiceCallJob1", "group1").Build();
                var trigger1 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger1", "group1").WithCronSchedule(ScheduleCronExpression).Build();
                await scheduler.ScheduleJob(job1, trigger1);
            } catch (Exception ex) {}
        }
    }
}

You’ve only completed one job in the code above. If you wish to execute more than one job, just create a new class, as we did with task1.

We will now add this job to task scheduler.

//First Task
var job1 = JobBuilder.Create < Task1 > ().WithIdentity("ExecuteTaskServiceCallJob1", "group1").Build();
var trigger1 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger1", "group1").WithCronSchedule(ScheduleCronExpression).Build();
// Second Task
var job2 = JobBuilder.Create < Task2 > ().WithIdentity("ExecuteTaskServiceCallJob2", "group2").Build();
var trigger2 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger2", "group2").WithCronSchedule(ScheduleCronExpression).Build();
await scheduler.ScheduleJob(job1, trigger1);
await scheduler.ScheduleJob(job2, trigger2);

You’ve just seen the ScheduleCronExpression in the code above. The cron expression is a format that specifies how often your task will be performed.

Below I give you some examples,

Every Second : * * * ? * *
Every Minute : 0 * * ? * *
Every Day noon 12 pm : 0 0 12 * * ?

A list of cron expressions may be found at the URL. You may create your own cron expressions as well.

https://www.freeformatter.com/cron-expression-generator-quartz.html

 Final Step

Now register your scheduler task to startup.

public Startup(IConfiguration configuration) {
    //The Schedular Class
    SchedulerTask.StartAsync().GetAwaiter().GetResult();
    Configuration = configuration;
}

All you have to do now is run your code and check your text file, which is often running at the time you set in the cron expression.

Conclusion

In this blog, we learned how to schedule a task in asp.net core, which we can use to perform any operation, such as sending mail at a certain time. As a result, we can perform any operation with this, and it’s quite easy to set up.