【问题标题】:raise an event on the server after certain delay在一定延迟后在服务器上引发事件
【发布时间】:2016-03-30 07:33:40
【问题描述】:

我正在开发 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 的执行,我的方法是正确的还是应该以其他方式进行?实现它的最佳方法是什么?

【问题讨论】:

标签: asp.net asp.net-mvc timer


【解决方案1】:

您可以使用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);
    }
}

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多