Quartz.net setup in an asp.net website

Did you try the quartz.net tutorial?

Since your web app might get recycled/restarted, you should probably (re-)intialize the quartz.net scheduler in the Application_Start handler in global.asax.cs.


Update (with complete example and some other considerations):

Here’s a complete example how to do this using quartz.net. First of all, you have to create a class which implements the IJobinterface defined by quartz.net. This class is called by the quartz.net scheduler at tne configured time and should therefore contain your send mail functionality:

using Quartz;
public class SendMailJob : IJob
{
    public void Execute(JobExecutionContext context)
    {
        SendMail();
    }
    private void SendMail()
    {
        // put your send mail logic here
    }
}

Next you have to initialize the quartz.net scheduler to invoke your job once a day at 06:00. This can be done in Application_Start of global.asax:

using Quartz;
using Quartz.Impl;

public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        ISchedulerFactory schedFact = new StdSchedulerFactory();
        // get a scheduler
        IScheduler sched = schedFact.GetScheduler();
        sched.Start();
        // construct job info
        JobDetail jobDetail = new JobDetail("mySendMailJob", typeof(SendMailJob));
        // fire every day at 06:00
        Trigger trigger = TriggerUtils.MakeDailyTrigger(06, 00);
        trigger.Name = "mySendMailTrigger";
        // schedule the job for execution
        sched.ScheduleJob(jobDetail, trigger);
    }
    ...
}

That’s it. Your job should be executed every day at 06:00. For testing, you can create a trigger which fires every minute (for example). Have a look at the method of TriggerUtils.

While the above solution might work for you, there is one thing you should consider: your web app will get recycled/stopped if there is no activity for some time (i.e. no active users). This means that your send mail function might not be executed (only if there was some activity around the time when the mail should be sent).

Therefore you should think about other solutions for your problem:

  • you might want to implement a windows service to send your emails (the windows service will always be running)
  • or much easier: implement your send mail functionality in a small console application, and set up a scheduled task in windows to invoke your console app once a day at the required time.

Leave a Comment