Scheduling In ASP.NET MVC Core

Introduction

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

Step 1: To start, create a project using the ASP.NET Core web application template and select Asp.net MVC for your web application.

Step 2: There are two ways to install the Quartz package: search for Quartz in the NuGet package manager and install it, or download the package from the official website and install it manually.

Scheduling in asp.net MVC Core

I am using the NuGet package manager console.

Scheduling in asp.net MVC Core

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 will 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 provided 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, create a folder named "log" under the C drive. Inside this folder, create a text file called sample.txt.

Scheduler task

We will now create a new class responsible for triggering the task. This class's role is to initiate the established task and set its frequency of execution.

Below is the code of the class,

using Quartz;
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 have only completed one job in the code above. If you wish to execute more than one job, simply create a new class, as we did with task 1.

We will now add this job to the 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 have just viewed 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 can be found at the URL, and you can also create your cron expressions.

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 our blog, we covered the process of scheduling a task in ASP.NET Core. This scheduling functionality can be utilized for various operations, like sending emails at specific times. It's a straightforward setup and allows for a wide range of operations to be performed.