Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

Scheduled Tasks In ASP.NET With Quartz.Net

Posted By: Ajay Saptaputre, 20 Oct,2015  |  Total View : 10313

In my previous article I discussed about CRUD Operations Using MVCContrib Grid with ASP.NET MVC 5 and Entity Framework 6 and How Email Can be Used to Track User IP address Using ASP.NET and NLog to provide custom tracing for your ASP.NET

In this article I am going to discuss how to schedule background task in ASP.NET using Quartz.Net. If you are a .Net developer and asked to send emails once in 24 hours at a given time, what will you do? You may go to write Windows Services and install or write console application and schedule with the Task Scheduler. However writing scheduler using Windows Services, you may require special technical skills and installation privileges at server whereas for scheduling console application (EXE) in Task Scheduler requires special privileges at server. So what is the solution? The answer is Quartz.Net.

What is Quartz.Net?

Quartz.NET is open source job scheduling .NET library which can be used to schedule task from small application to large scale enterprise application. Quartz.Net fully featured open source scheduling library which is available at nuget. In this article I am going to discuss how to schedule simple background task in ASP.NET using Quartz.Net.

Quartz.Net has three major components - Job, Trigger and Scheduler.

  • Job - A task to be performed.
  • Trigger - Decide how and when the job is executed.
  • Scheduler - This will make sure that the job is performed on a given time.

Quartz.Net Installing

In order to use Quartz.Net, you simply need to install Quartz.Net package. So, right click on your Visual Studio project and select "Manage NuGet Packages", search "Quartz.Net" and click on "Add" from result list or you can use following command in the Package Manager Console:


Install-Package Quartz.Net

Quartz.Net Implementation

Now, right click on your project and add new class file, rename as "EmailJob.cs" and add below code to the file. In order to work with Quartz.Net, "EmailJob" class must implement "IJob" interface and give implementation for "Execute" method of "IJob" interface. The "Execute" method will perform an action. Notice that the "Execute" method takes context as parameter called "IJobExecutionContext". The "IJobExecutionContext" context contains all the configuration information related to the job. In this example I am sending an email using "SendHtmlFormattedEmail" method. See below code snippet:

using Quartz;
using System.IO;
using System.Net.Mail;
using System.Net;
using System;
using System.Configuration;
using System.Web;
using System.Web.UI;

namespace QuartZExample
{
public class EmailJob : IJob
{
/// <summary>
/// Automatically execute this function by Quartz.Net
/// </summary>
/// <param name="context"></param>
public void Execute(IJobExecutionContext context)
{
	this.SendHtmlFormattedEmail("[email protected]", 
	"SchedulerEmail", this.PopulateBody());
}

/// <summary>
/// Sending Scheduler email to user using Quartz.Net
/// </summary>
/// <param name="recepientEmail"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
	using (MailMessage mailMessage = new MailMessage())
	{
		mailMessage.From = 
		new MailAddress(ConfigurationManager.AppSettings["MailAddress"]);
		mailMessage.Subject = subject;
		mailMessage.Body = body;
		mailMessage.IsBodyHtml = true;
		mailMessage.To.Add(new MailAddress(recepientEmail));
		SmtpClient smtp = new SmtpClient();
		smtp.Host = ConfigurationManager.AppSettings["Host"];
		System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
		NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
		NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
		smtp.UseDefaultCredentials = true;
		smtp.Credentials = NetworkCred;
		smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
		smtp.Send(mailMessage);
	}
}
/// <summary>
/// Return HTML template body
/// </summary>
/// <returns></returns>
private string PopulateBody()
{
	string body = string.Empty;
	using (StreamReader reader = 
	new StreamReader(HttpContext.Current.Server.MapPath("~/TestMail.htm")))
	{
		body = reader.ReadToEnd();
	}
	return body;
}
}
}

In order execute job, you need to schedule the created job. So, let's add another class file rename it; in this example "JobScheduler.cs". Notice in below code snippet, job is created by calling "Create" method of "JobBuilder" object which is belong to Quartz.Net. The "Create" method takes (type) for job creation, in this example "EmailJob". Next, trigger is created by passing created job object, in this example "emailJob". Trigger is used to set when the job should execute. In this example, the scheduler is starting daily at midnight 12PM from "Mon" to "Friday". You can find more about triggers and schedulers from here.

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QuartZExample
{
    public class JobScheduler
    {
	/// <summary>
	/// This function will start when application up and 
	runing and schedule cron job for email
	/// </summary>
	public static void Start()
	{
	IJobDetail emailJob = JobBuilder.Create()
		  .WithIdentity("job1")
		  .Build();

	ITrigger trigger = TriggerBuilder.Create()
		.WithDailyTimeIntervalSchedule
		  (s =>
			 s.WithIntervalInSeconds(30)
			.OnEveryDay()
		  )
		 .ForJob(emailJob)
		 .WithIdentity("trigger1")
		 .StartNow()
		 .WithCronSchedule("0 00 12 ? * MON-FRI *")
		 .Build();

	ISchedulerFactory sf = new StdSchedulerFactory();
	IScheduler sc = sf.GetScheduler();
	sc.ScheduleJob(emailJob, trigger);
	sc.Start();
        }
    }
}

Run Quartz.Net Job

So far you have created "Job", "Trigger" and register with scheduler. All right, now it's time to run the appliocation. To start job, you need to call "Start" method of "JobScheduler" in application start point. In ASP.NET application start point is Application_Start in the Global.asax file, so let's call "Start" method in Application_Start event:

<%@ Application Language="C#" %>
<%@ Import Namespace="QuartZExample" %>
<script runat="server">
void Application_Start(object sender, EventArgs e) 
{
	JobScheduler.Start();
}
</script>

Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩