Quartz.net配置和日程安排

时间:2016-07-19 16:57:18

标签: wpf windows-services quartz-scheduler quartz.net

我有一个WPF应用程序,用户在数据库中创建实体。每个实体都有一些元数据和一个区间字段。对于每个实体,我想创建一个提供间隔的作业,并将它们存储在AdoJobStore中。 现在,由于WPF应用程序不会一直运行,我想创建一个Windows服务,从AdoJobStore读取作业数据并运行这些作业。

所以基本上有这2层。现在我已经在现有数据库中设置了Quartz表。我的问题是:

  • 如何从我的WPF应用程序创建/编辑/删除作业
  • 如何通知我的Windows服务运行作业(每次在数据库中创建实体)

我已阅读了很多博客,但这两个主要问题对我来说有点不清楚。我真的很感激一些关于如何实现的示例代码,并且可能构建我的解决方案。

由于

1 个答案:

答案 0 :(得分:0)

您使用Zero Thread Scheduler来安排作业。示例调度程序初始化代码:

var properties = new NameValueCollection();
properties["quartz.scheduler.instanceId"] = "AUTO";
properties["quartz.threadPool.type"] = "Quartz.Simpl.ZeroSizeThreadPool, Quartz";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
properties["quartz.jobStore.useProperties"] = "true";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = tablePrefix;
properties["quartz.jobStore.clustered"] = "false";
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = "SqlServer-20";
schedFactory = new StdSchedulerFactory(properties);
BaseScheduler = schedFactory.GetScheduler();

示例调度功能:

    protected ITrigger CreateSimpleTrigger(string tName, string tGroup, IJobDetail jd, DateTime startTimeUtc,
        DateTime? endTimeUtc, int repeatCount, TimeSpan repeatInterval, Dictionary<string, string> dataMap, 
        string description = "")
    {
        if (BaseScheduler.GetTrigger(new TriggerKey(tName, tGroup)) != null) return null;

        var st = TriggerBuilder.Create().
            WithIdentity(tName, tGroup).
            UsingJobData(new JobDataMap(dataMap)).
            StartAt(startTimeUtc).
            EndAt(endTimeUtc).
            WithSimpleSchedule(x => x.WithInterval(repeatInterval).WithRepeatCount(repeatCount)).
            WithDescription(description).
            ForJob(jd).
            Build();               
        return st;
    }

显然,您需要在UI中提供所有相关字段,并将这些字段中的值传递到函数中。一些必填字段的示例屏幕截图:

Sample scheduling UI

您的Windows服务将以与上面初始化Zero Thread Scheduler的方式非常类似的方式初始化OnStart()方法中的多线程调度程序,并且Multi Thread Scheduler将监视数据库中的所有触发器并将您的作业启动为在那些触发器中指定。 Quartz.net将在这方面做所有繁重的工作。一旦您在数据库中安排了作业和触发器,您只需要初始化多线程调度程序,将其连接到包含触发器的数据库,并且只要服务正在运行,它就会继续触发这些作业并执行代码。