在.Net MVC中在运行时创建和调度作业

时间:2017-12-08 06:54:11

标签: c# asp.net-mvc quartz.net hangfire

我想创建一个报告调度程序,根据用户定义的时间自动发送附带报告的电子邮件。

用户可以指定报告的时间和发生,一旦保存,调度程序需要根据定义的设置在特定的时间/日运行,每个用户也可以独立定义自己的设置。

我从下面参考了SO回答

How to reschedule Quartz job scheduler in C# dynamically from database?

/// <summary>
/// Create a new trigger based on a existing trigger.
/// </summary>
/// <param name="oldTrigger">the existing trigger</param>
/// <param name="startNow">indicates if the trigger should start immediately after schedule</param>
/// <param name="interval">the interval for the new trigger</param>
/// <returns>Returns the new trigger</returns>
public ITrigger CreateTrigger(ITrigger oldTrigger, bool startNow = false, TimeSpan? interval = null)
{
    var builder = oldTrigger.GetTriggerBuilder();
    if (startNow)
        builder = builder.StartNow();
    if (interval.HasValue)
        builder = builder.WithSimpleSchedule(s => s
            .WithInterval(interval.Value)
            .RepeatForever());

    var newTrigger = builder.Build();
    var simpleTrigger = newTrigger as ISimpleTrigger;
    if(simpleTrigger != null)
    {
        var trigger = oldTrigger as ISimpleTrigger;
        if (trigger != null)
            simpleTrigger.TimesTriggered = trigger.TimesTriggered;
    }

    return newTrigger;
}

如何使用

In this example, the Scheduler is already running.
// get the trigger
var trigger = Scheduler.GetTrigger(new TriggerKey("trigger1", "group1"));

// get your settings and set the interval
var reminderSettings = GetReminderSettings();
var intervalBtwnReminders = 0;
if (reminderSettings?.RemindersGap != null)
{
    intervalBtwnReminders = (int)(reminderSettings.RemindersGap);         
}

// reschedule the job with a new trigger and start it immediately.
// if you don't want that it starts now, pass 'false' for the 'startNow' parameter
Scheduler.RescheduleJob(trigger.Key, CreateTrigger(trigger, true, TimeSpan.FromMinutes(intervalBtwnReminders)));

问题:

以上代码显示重新安排作业,但我想在每次用户保存时创建新的调度程序。

如果两个用户定义了相同的时序,那么Quartz.Net也能同时工作?

有没有更好的方法可用,或者这种方法有任何性能问题吗?

1 个答案:

答案 0 :(得分:0)

Hangfire解决了上述所有问题