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


Answers:


77

您有两种选择,具体取决于您要执行的操作和设置方式。例如,您可以将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.Net入门人员撰写的一些帖子的链接:http ://jvilalta.blogspot.com/2009/03/getting-started-with-quartznet-part-1.html


1
您可以更新使用最新版本的帖子等吗?看来配置值的格式现在不同了。谢谢!
斯诺伊

我认为2.x的更新方法是:#将此服务器导出到远程上下文quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter,Quartz crystal.scheduler.exporter.port = 555quartz.scheduler.exporter.bindName = QuartzScheduler crystal.scheduler.exporter.channelType = tcp crystal.scheduler.exporter.channelName = httpQuartz
NickG 2013年

啊 讨厌评论中不能有新行!
NickG

2

几周前,我写过有关使用Quartz.Net计划Windows Azure Worker角色中的作业的信息。从那时起,我遇到了一项要求,促使我围绕Quartz.Net IScheduler创建包装器。JobSchedule负责从CloudConfigurationManager读取计划字符串并计划作业。

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

以下示例将安排一项工作,该工作每天需要在6 AM,8 AM,10 AM,12:30 PM和4:30 PM执行。该计划在“角色”设置中定义,可以通过Visual Studio进行编辑。若要进行角色设置,请转到Windows Azure云服务项目,然后在“角色”文件夹下找到所需的角色配置。双击配置文件打开配置编辑器,然后导航到“设置”选项卡。单击“添加设置”并将新设置命名为“ 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));

DailyJob实现如下。由于这是一个演示,因此我不会在作业中添加任何特定的逻辑。

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

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

应在角色启动时配置JobSchedule,并应在角色的整个生命周期中维护JobSchedule实例。可以通过Windows Azure管理门户在云服务的“配置”部分下更改“ JobDailySchedule”设置来更改计划。然后,要应用新计划,请通过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);
        });
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.