我正在开发ASP.NET5应用程序,我想在一定延迟后在服务器上触发事件。我还希望客户端能够向服务器发送请求以取消事件的执行。
如何保留Timer
,以便我可以通过致电Change(Timeout.Infinite, Timeout.Infinite)
在其他请求中取消?
public class ApiController : Controller
{
public IActionResult SetTimer()
{
TimerCallback callback = new TimerCallback(EventToRaise);
Timer t = new Timer(callback, null, 10000, Timeout.Infinite);
//I need to persist Timer instance somehow in order to cancel the event later
return HttpOkObjectResult(timerId);
}
public IActionResult CancelTimer(int timerId)
{
/*
here I want to get the timer instance
and call Change(Timeout.Infinite, Timeout.Infinite)
in order to cancel the event
*/
return HttpOkResult();
}
private void EventToRaise(object obj)
{
///..
}
}
我正在使用System.Threading.Timer来延迟EventToRaise
的执行,我的方法是正确的,还是应该以其他方式执行?实现它的最佳方法是什么?
答案 0 :(得分:0)
您可以使用Quartz.NET,如下所示。另一方面,对于基于IIS的触发问题,请查看我在Quartz.net scheduler doesn't fire jobs/triggers once deployed上的答案。
<强> 的Global.asax: 强>
protected void Application_Start()
{
JobScheduler.Start();
}
<强> EmailJob.cs: 强>
using Quartz;
public class EmailJob : IJob
{
public void Execute(IJobExecutionContext context)
{
SendEmail();
}
}
<强> JobScheduler.cs: 强>
using Quartz;
using Quartz.Impl;
public class JobScheduler
{
public static void Start()
{
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
IJobDetail job = JobBuilder.Create<EmailJob>().Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
//.StartAt(new DateTime(2015, 12, 21, 17, 19, 0, 0))
.StartNow()
.WithSchedule(CronScheduleBuilder
.WeeklyOnDayAndHourAndMinute(DayOfWeek.Monday, 10, 00)
//.WithMisfireHandlingInstructionDoNothing() //Do not fire if the firing is missed
.WithMisfireHandlingInstructionFireAndProceed() //MISFIRE_INSTRUCTION_FIRE_NOW
.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("GTB Standard Time")) //(GMT+02:00)
)
.Build();
scheduler.ScheduleJob(job, trigger);
}
}
希望这会有所帮助......