Today We gonna see that how the Quartz Scheduler will work in MVC and the application is configure in IIS.
Step-1: Open VS 2017 >> File New Project >> ASP .NET application >> Choose Empty MVC
You can install it through Package Manager Console of the following command.
Install-Package Quartz -Version 3.0.7
<add key="TaskService" value="ON" />
<add key="SchedularService" value="0 0/1 * 1/1 * ? *" />
using Quartz;
using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
namespace QuartzSchedularMVC.Models
{
public class TaskService : IJob
{
public static readonly string SchedulingStatus = ConfigurationManager.AppSettings["TaskService"];
public Task Execute(IJobExecutionContext context)
{
var task = Task.Run(() =>
{
if (SchedulingStatus.Equals("ON"))
{
try
{
string path = "C:\\Sample.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format("Quartz Schedular Called on "+ DateTime.Now.ToString("dd /MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
catch (Exception ex)
{
}
}
});
return task;
}
}
}
(ii) Add another class under Models Folder named as "SchedulerService.cs"
using Quartz;
using Quartz.Impl;
using System;
using System.Configuration;
namespace QuartzSchedularMVC.Models
{
public class SchedulerService
{
private static readonly string ScheduleCronExpression = ConfigurationManager.AppSettings["SchedularService"];
public static async System.Threading.Tasks.Task StartAsync()
{
try
{
var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
if (!scheduler.IsStarted)
{
await scheduler.Start();
}
var job = JobBuilder.Create<TaskService>()
.WithIdentity("ExecuteTaskServiceCallJob1", "group1")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity("ExecuteTaskServiceCallTrigger1", "group1")
.WithCronSchedule(ScheduleCronExpression)
.Build();
await scheduler.ScheduleJob(job, trigger);
}
catch (Exception ex)
{
}
}
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
//The Schedular Class
SchedulerService.StartAsync().GetAwaiter().GetResult();
}
}
In every 1 minute interval this process execute. if you want to change the schedule time you can change through Web.config Key |
Step-6: Now we run our application and see the output in printed in Notepad in every 1 minute interval as expected.
Please follow how to configure MVC application in IIS.
Please find the Source code in GitHub
Summary
Post a Comment