- Defining Job
- Job Trigger
- Job Schedule
Job is the task, Job Trigger is when the job is executed. Job and trigger are combined for execution with the JobScheduler . We have to create a job class which implements the IJob interface defined by quartz.net. This class is called by the quartz.net scheduler at the configured time and should therefore contain your send mail functionality
Defining Job
A job is a class. It implements the Quartz IJob interface and this method defines actions to be performed. The Execute method get IJobExecutionContext object as a parameter. The scheduler passes that in when calling the job's Execute method.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Quartz;
- using System.Net;
- using System.Net.Mail;
-
-
- namespace ScheduledTask.Models
- {
- public class Jobclass:IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- using (var message = new MailMessage("[email protected]", "[email protected]"))
- {
- message.Subject = "Message Subject test";
- message.Body = "Message body test at " + DateTime.Now;
- using (SmtpClient client = new SmtpClient
- {
- EnableSsl = true,
- Host = "smtp.gmail.com",
- Port = 587,
- Credentials = new NetworkCredential("[email protected]", "123546")
- })
- {
- client.Send(message);
- }
- }
- }
- }
-
- }
Job Trigger
Actual code has been placed in a method called Start A scheduler is created and started the job is created using the Quartz.NET JobBuilder.Create<Jobclass> method, where Jobclass is the type of job to be created. Then a trigger is created when a Job should be executed.
We want to run this Job WithIntervalInSeconds once in Seconds . So our trigger definition will look like,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Quartz;
- using Quartz.Impl;
-
- namespace ScheduledTask.Models
- {
- public class JobScheduler
- {
- public static void Start()
- {
- IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
- scheduler.Start();
-
- IJobDetail job = JobBuilder.Create<Jobclass>().Build();
-
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("trigger1", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(10)
- .RepeatForever())
- .Build();
-
- scheduler.ScheduleJob(job, trigger);
- }
- }
- }
There are different types of triggers – Time based, Calendar, Schedule, etc.
JobScheduler in Global asax
The Application_Start event handler in the Global.asax.cs file place for invoke the start method of the JobScheduler.Start, as it would be called the first time the application is started.
Summary:
We learned open source job Scheduling Background Tasks in ASP.NET using Quartz.NET. I hope this article is useful for all .NET beginners.
Read more articles on ASP.NET: