我刚刚将quartz.net dll添加到我的bin中,并开始了我的示例。如何根据时间使用quartz.net调用C#方法?
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 = "[email protected]";
mail.From = "[email protected]";
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", "[email protected]");
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;
}
}
}
这里我只是在加载页面时发送邮件。如何使用quartz.net在给定的时间(例如6.00 AM)每天一次调用SendMail()
?我不知道如何开始。我应该在global.asax
文件中对其进行配置吗?有什么建议吗?
您是否尝试过quartz.net tutorial?
由于您的Web应用可能会被回收/重新启动,因此您可能应该在global.asax.cs的Application_Start处理程序中(重新)初始化quartz.net调度程序。
更新(带有完整的示例和其他注意事项):
这里是一个完整的示例,说明如何使用quartz.net执行此操作。首先,您必须创建一个类来实现quartz.net定义的IJob
接口。该类由quartz.net调度程序在配置的时间调用,因此应包含您的发送邮件功能:
using Quartz;
public class SendMailJob : IJob
{
public void Execute(JobExecutionContext context)
{
SendMail();
}
private void SendMail()
{
// put your send mail logic here
}
}
接下来,您必须初始化quartz.net调度程序,以每天06:00调用一次作业。这可以在Application_Start
的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);
}
...
}
就是这样。您的工作应该每天06:00执行。为了进行测试,您可以创建一个每分钟触发一次的触发器(例如)。看看TriggerUtils
的方法。
虽然上述解决方案可能对您有用,但您应该考虑一件事:如果一段时间内没有任何活动(即没有活动的用户),您的网络应用将被回收/停止。这意味着您的“发送邮件”功能可能不会执行(仅在应发送邮件的时间内有一些活动)。
因此,您应该考虑其他解决问题的方法:
除了提供M4N的良好答案之外,您还可以查看spring.net integration of the quartz.net lib,它允许调用方法而无需实现IJob。
在schedFact.GetScheduler()末尾添加.Result。
i搜索Quartz。我这样做是为了我的工作: