-1

I am developing ASP.NET5 Application and I want to trigger an event on the server after certain delay. I also want client to be able to send a request to the server to cancel the execution of the event. How can I persist a Timer, so I can cancel it in another request by calling 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)
   {
      ///..
   }
}

I am using System.Threading.Timer to delay the execution of the EventToRaise, is my approach correct or should I do it some other way ? What is the best way to achieve it ?

koryakinp
  • 3,989
  • 6
  • 26
  • 56

1 Answers1

0

You can use Quartz.NET as shown below. On the other hand, for IIS based triggering problems, have a look at my answer on 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);
    }
}

Hope this helps...

Community
  • 1
  • 1
Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63