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.
Quartz.Net has three major components - Job, Trigger and Scheduler.
Install-Package Quartz.Net
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
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();
}
}
}
<%@ Application Language="C#" %>
<%@ Import Namespace="QuartZExample" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
JobScheduler.Start();
}
</script>
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...