a blog for those who code

Wednesday, 13 July 2016

Jobs and Triggers in Quartz.Net

In this post we will be discussing about Jobs and Triggers in Quartz.Net scheduler. Jobs and triggers are core of the Quartz.Net scheduler i.e. job do the work and triggers determine when the work to be done. In our previous post we have discussed about creating scheduled jobs in Asp.Net application, here we will give the detailed explanation of Job and Triggers.

Quartz.Net Jobs

Creating a Quartz.Net is very easy, just that you need to implement IJob Interface. It will have a execute method which takes JobExecutionContext object as a parameter. When the job will be trigger, the Execute() method will be invoked. The JobExecutionContext object will provide the information about job's execution environment. The simple job is shown below :

class MyJob : IJob
  public void Execute(IJobExecutionContext context)
    // Sending Emails 

JobDataMap in Jobs

JobDatamap is used to pass parameters to the job i.e. it can be used to hold the number of serialiable objects available to the job instance when it executes. You can get the JobDataMap object from the context as shown below:

JobDataMap jd = context.JobDetail.JobDataMap;

The JobDataMap can be Stateful and Non-Stateful. Non-Stateful jobs only have their JobDataMap stored at the time they are added to the scheduler but changes made to the contents will be lost next time it executes. Whereas in Stateful jobs, its JobDataMap is re-stored after every execution of the job.

Quartz.Net Triggers

Triggers determine when the job will be executed. A job can have zero or more triggers whereas a trigger can only be assigned to one job. A job with zero trigger will never execute. A trigger is also uniquely identified by its Name and Group properties. An example of trigger is shown below :

ITrigger trigger1 = TriggerBuilder.Create()
         .WeeklyOnDayAndHourAndMinute(DayOfWeek.Tuesday, 9, 0)

In the above example we have created a trigger with cron schedule builder which will run weekly on Tuesday at 9'o clock morning UTC time zone.

And then using the scheduler we will schedule the job using the below command where job1 is the job and trigger1 is the trigger :

scheduler.ScheduleJob(job1, trigger1);

Full Code

using System;
using Quartz;
using Quartz.Impl;

namespace SchedulingTasks
  public class JobScheduler
    public static void Start()
      IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

      IJobDetail job = JobBuilder.Create<MyJob>().Build();

      ITrigger trigger = TriggerBuilder.Create()
            .WeeklyOnDayAndHourAndMinute(DayOfWeek.Tuesday, 11, 0)

      scheduler.ScheduleJob(job, trigger);

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us


Email *

Message *


Best Hosting Plans

CC License