2016-03-29 20 views
-1

我正在开发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的执行,是我的方法正确,或者我应该做一些其他的方式?实现它的最好方法是什么?

+1

阅读本=> http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx – CodeNotFound

+0

@CodeNotFound谢谢先生,我想我会按照文章中的建议使用Hangfire。 – koryakinp

回答

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); 
    } 
} 

希望这有助于...

相关问题