如何在ASP.NET中使用Quartz.net调度任务以触发邮件发送?

72

我不知道如何在ASP.NET中使用Quartz.dll。我们应该在哪里编写代码以定时触发每天早上发送邮件的任务?

2个回答

77
你有几个选项,具体取决于你想做什么和如何设置。例如,你可以将Quartz.Net服务器安装为独立的Windows服务,也可以将其嵌入到ASP.NET应用程序中。
如果你想嵌入运行它,那么你可以从全局.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.Net的人了解更多: http://jvilalta.blogspot.com/2009/03/getting-started-with-quartznet-part-1.html


1
你能更新使用最新版本的帖子等内容吗?现在配置值的格式似乎已经改变了。谢谢! - Snowy
我认为2.x版本的新方法是:

将此服务器导出到远程上下文

quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz quartz.scheduler.exporter.port = 555 quartz.scheduler.exporter.bindName = QuartzScheduler quartz.scheduler.exporter.channelType = tcp quartz.scheduler.exporter.channelName = httpQuartz
- NickG
啊,讨厌注释里不能换行! - NickG

2
几周前,我写了一篇关于使用Quartz.Net在Windows Azure Worker Roles中调度作业的文章。自那以后,我遇到了一个要求,这促使我创建了一个包装器来包装Quartz.Net IScheduler。JobSchedule负责从CloudConfigurationManager读取计划字符串并安排作业。
CloudConfigurationManager从角色配置文件中读取设置,可以通过Windows Azure管理门户下的云服务配置部分进行编辑。
以下示例将安排一个需要每天在早上6点、8点、10点、下午12:30和下午4:30执行的作业。计划在角色设置中定义,可以通过Visual Studio进行编辑。要访问角色设置,请转到Windows Azure Cloud Service项目,并在Role文件夹下找到所需的角色配置。双击配置文件打开配置编辑器,然后导航到“设置”选项卡。单击“添加设置”,将新设置命名为“JobDailySchedule”,并将其值设置为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.

然后使用JobSchedule根据角色配置文件中定义的计划安排每日作业。
var schedule = new JobSchedule();

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

每日作业的实现如下。由于这只是一个演示,我不会添加任何特定的逻辑到作业中。
public class DailyJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        //Do your daily work here
    }
}

JobSchedule包装了Quartz.Net IScheduler。在之前的文章中,我谈到了包装第三方工具的重要性,这是一个很好的例子,因为我正在包含作业调度逻辑,并且我有可能在不影响使用JobSchedule的代码的情况下更改此逻辑。

应在角色启动时配置JobSchedule,并在整个角色生命周期内维护JobSchedule实例。可以通过在云服务的配置部分下更改“JobDailySchedule”设置来更改计划。然后,在云服务的实例部分下重新启动角色实例以应用新计划。

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);
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接