Quartz.net setup in an asp.net website

I’ve just added quartz.net dll to my bin and started my example. How do I call a C# method using quartz.net based on time?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Quartz;
using System.IO;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(SendMail())
             Response.write("Mail Sent Successfully");
    }
   public bool SendMail()
   {
    try
    {
        MailMessage mail = new MailMessage();
        mail.To = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b1a0b6b185b1a0b6b1eba6aaa8">[email protected]</a>";
        mail.From = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d3c1cdd0ccc5e0d3c1cdd0ccc58ec3cfcd">[email protected]</a>";
        mail.Subject = "Hai Test Web Mail";
        mail.BodyFormat = MailFormat.Html;
        mail.Body = "Hai Test Web Service";
        SmtpMail.SmtpServer = "smtp.gmail.com";
        mail.Fields.Clear();
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f7e0e1f2eae9e3c5e2e8e4ece9abe6eae8">[email protected]</a>");
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "************");
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
        SmtpMail.Send(mail);
        return (true);
    }
    catch (Exception err)
    {
        throw err;
    }
}
}

Here I am just sending a mail on page load. How do I call SendMail() once in a day at a given time (say 6.00 AM) using quartz.net? I don’t know how to get started. Should I configure it in my global.asax file? Any suggestion?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

In addition to the good answer M4N provided, you can take a look at the spring.net integration of the quartz.net lib which allows to call methods without the need to implement IJob.

Method 3

Add .Result at the end of schedFact.GetScheduler();

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

Method 4

i searching for Quartz . i do this for my job:

1:instal Quartz from visual console:

PM> Install-Package quartz

2:create a class like this:

using Quartz;
public class Quartz : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        //do some 
    }
}

3.in global
using Quartz;
using Quartz.Impl;

    protected void Application_Start(object sender, EventArgs e)
    {
        //for start time at first run after 1 hour
        DateTimeOffset startTime = DateBuilder.FutureDate(1, IntervalUnit.Hour);
        IJobDetail job = JobBuilder.Create<Quartz>()
                                   .WithIdentity("job1")
                                   .Build();
        ITrigger trigger = TriggerBuilder.Create()
                                         .WithIdentity("trigger1")
                                         .StartAt(startTime)
                                         .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(2))
                                         .Build();
        ISchedulerFactory sf = new StdSchedulerFactory();
        IScheduler sc = sf.GetScheduler();
        sc.ScheduleJob(job, trigger);
        sc.Start();
    }

it is code that doing some job in every 10second for 3time.
good luck


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x