如何在 ASP.NET 中使用 Quartz.net

我不知道如何在 ASP.NET 中使用 Quartz.dll。在哪里编写代码来安排每天早上触发邮件的作业?如果有人知道,请帮帮我。

编辑: 我发现 如何以专业的方式使用 Quartz.NET?真的很有用。

44084 次浏览

您有几个选项,这取决于您想要做什么以及您想要如何设置它。例如,您可以安装 Quartz。Net 服务器作为一个独立的 Windows 服务器,或者您也可以将其嵌入到 asp.Net 应用程序中。

如果你想运行它嵌入式,那么你可以从 global.asax 启动服务器,像这样(源代码例子,例子 # 12) :

NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServer";


// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";


ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
sched.Start();

如果你将它作为一个服务来运行,你可以像下面这样远程连接它(例子 # 12) :

NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteClient";


// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";


// set remoting expoter
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();

一旦有了对调度程序的引用(可以通过远程处理,也可以通过嵌入式实例) ,就可以像下面这样调度作业:

// define the job and ask it to run
JobDetail job = new JobDetail("remotelyAddedJob", "default", typeof(SimpleJob));
JobDataMap map = new JobDataMap();
map.Put("msg", "Your remotely added job has executed!");
job.JobDataMap = map;
CronTrigger trigger = new CronTrigger("remotelyAddedTrigger", "default", "remotelyAddedJob", "default", DateTime.UtcNow, null, "/5 * * ? * *");
// schedule the job
sched.ScheduleJob(job, trigger);

下面是我为那些刚开始使用 Quartz 的人写的一些文章的链接: Http://jvilalta.blogspot.com/2009/03/getting-started-with-quartznet-part-1.html

几周前,我写了一篇关于使用 Quartz 的文章。Net 将在 WindowsAzure 工作者角色中安排作业。从那时起,我遇到了一个需求,这个需求促使我创建了一个石英的包装器。网络调度程序。JobScheme 负责从 CloudConfigurationManager 读取调度字符串并调度作业。

CloudConfigurationManager 从角色的配置文件中读取设置,可以通过 Windows Azure 管理门户在云服务的配置部分进行编辑。

下面的示例将安排需要在每天早上6点、8点、10点、12点30分和4点30分执行的作业。调度在可通过 VisualStudio 编辑的“角色”设置中定义。要访问角色设置,请转到 Windows Azure 云服务项目,并在“角色”文件夹下找到所需的角色配置。通过双击配置文件打开配置编辑器,然后导航到“设置”选项卡。点击“添加设置”并将新设置命名为“ JobDailyScheme”,并将其值设置为6:0; 8:0; 10:0; 12:30; 16:30;

The code from this Post is part of the Brisebois.WindowsAzure NuGet Package


To install Brisebois.WindowsAzure, run the following command in the Package Manager Console


PM> Install-Package Brisebois.WindowsAzure


Get more details about the Nuget Package.

然后,使用在角色的配置文件中定义的调度来调度每日作业。

var schedule = new JobSchedule();


schedule.ScheduleDailyJob("JobDailySchedule",
typeof(DailyJob));

DailyJob 的实现如下。由于这是一个演示,我不会添加任何具体的工作逻辑。

public class DailyJob : IJob
{
public void Execute(IJobExecutionContext context)
{
//Do your daily work here
}
}

作业计划包装了石英。网络调度程序。在上一篇文章中,我谈到了包装第三方工具的重要性,这是一个很好的例子,因为我包含了作业调度逻辑,我可以在不影响使用作业调度的代码的情况下潜在地更改这个逻辑。

应该在角色启动时配置 JobScheme,并且应该在角色的整个生命周期中维护 JobScheme 实例。通过云服务配置部分下的 Windows Azure 管理门户,可以通过更改“ JobDailyScheme”设置来更改时间表。然后应用新的调度,通过云服务的实例部分下的 Windows Azure 管理门户重新启动角色实例。

public class JobSchedule
{
private readonly IScheduler sched;


public JobSchedule()
{
var schedFact = new StdSchedulerFactory();


sched = schedFact.GetScheduler();
sched.Start();
}


/// <summary>
/// Will schedule jobs in Eastern Standard Time
/// </summary>
/// <param name="scheduleConfig">Setting Key from your CloudConfigurations,
///                              value format "hh:mm;hh:mm;"</param>
/// <param name="jobType">must inherit from IJob</param>
public void ScheduleDailyJob(string scheduleConfig,
Type jobType)
{
ScheduleDailyJob(scheduleConfig,
jobType,
"Eastern Standard Time");
}


/// <param name="scheduleConfig">Setting Key from your CloudConfigurations,
///                              value format "hh:mm;hh:mm;"</param>
/// <param name="jobType">must inherit from IJob</param>
public void ScheduleDailyJob(string scheduleConfig,
Type jobType,
string timeZoneId)
{
var schedule = CloudConfigurationManager.GetSetting(scheduleConfig);
if (schedule == "-")
return;


schedule.Split(';')
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToList()
.ForEach(h =>
{
var index = h.IndexOf(':');
var hour = h.Substring(0, index);
var minutes = h.Substring(index + 1, h.Length - (index + 1));


var job = new JobDetailImpl(jobType.Name + hour + minutes, null,
jobType);


var dh = Convert.ToInt32(hour, CultureInfo.InvariantCulture);
var dhm = Convert.ToInt32(minutes, CultureInfo.InvariantCulture);
var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);


var cronScheduleBuilder = CronScheduleBuilder
.DailyAtHourAndMinute(dh, dhm)
.InTimeZone(tz);
var trigger = TriggerBuilder.Create()
.StartNow()
.WithSchedule(cronScheduleBuilder)
.Build();


sched.ScheduleJob(job, trigger);
});
}


/// <summary>
/// Will schedule jobs in Eastern Standard Time
/// </summary>
/// <param name="scheduleConfig">Setting Key from your CloudConfigurations,
///                              value format "hh:mm;hh:mm;"</param>
/// <param name="jobType">must inherit from IJob</param>
public void ScheduleWeeklyJob(string scheduleConfig,
Type jobType)
{
ScheduleWeeklyJob(scheduleConfig,
jobType,
"Eastern Standard Time");
}




/// <param name="scheduleConfig">Setting Key from your CloudConfigurations,
///                              value format "hh:mm;hh:mm;"</param>
/// <param name="jobType">must inherit from IJob</param>
public void ScheduleWeeklyJob(string scheduleConfig,
Type jobType,
string timeZoneId)
{
var schedule = CloudConfigurationManager.GetSetting(scheduleConfig);


schedule.Split(';')
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToList()
.ForEach(h =>
{
var index = h.IndexOf(':');
var hour = h.Substring(0, index);
var minutes = h.Substring(index + 1, h.Length - (index + 1));


var job = new JobDetailImpl(jobType.Name + hour + minutes, null,
jobType);


var dh = Convert.ToInt32(hour, CultureInfo.InvariantCulture);
var dhm = Convert.ToInt32(minutes, CultureInfo.InvariantCulture);
var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var builder = CronScheduleBuilder
.WeeklyOnDayAndHourAndMinute(DayOfWeek.Monday,
dh,
dhm)
.InTimeZone(tz);


var trigger = TriggerBuilder.Create()
.StartNow()
.WithSchedule(builder)
.Build();


sched.ScheduleJob(job, trigger);
});
}
}