我在C#.Net网站中包含了Quartz.net库,可根据某些条件自动发送电子邮件。我已经使用RepeatForever()开始了这项工作。我从数据库中获取调度程序的设置。现在,当作业已经启动时,无论如何都要检查数据库中调度程序的设置是否已更改,所以我还应该在我的方法中更新它们,以便调度程序动态运行新设置?到目前为止,我已经这样做了:
CTSTR
答案 0 :(得分:5)
我写了一套方法让它变得更容易。
您无法使用新间隔编辑现有触发器,但可以使用新触发器替换现有触发器。
CreateTrigger
方法基于旧方法创建新的触发器并传输TimesTriggered
计数。
/// <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;
}
如何使用
在此示例中,调度程序已在运行。
// 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)));