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 ?