Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a method after a delay?

I'm writing an MVC 4 windows service that receives messages, analyzes them and sends a response. In certain cases I want the response to be delayed by a few minutes. I understand how to use the System.Threading.Timer to execute a method after a delay, but I think that any reference to the timer object would be gone when the processing method ends, allowing the timer to be garbage collected, right?

I've pretty much decided I need to keep a static list of timers somewhere, adding a reference when the timer is created and removing it (and call Timer.Dispose()) when the callback method is called.

Is there an easier way?

like image 618
William T. Mallard Avatar asked Dec 28 '25 01:12

William T. Mallard


2 Answers

First, you should read Phil Haack's article, The Dangers of Implementing Recurring Background Tasks In ASP.NET.

Then assuming you really want to do this, have the web application start a timer in the global.asax method Application_Start() such that it will fire on the frequency that you want. That timer should be static property of the application itself and the event handler that gets invoked should likewise be a static method of the application.

You'll also need a priority queue of items needed processing where each item is timestamped with its due date/time and the priority is the due date/time. Don't forget to synchronize access to the queue.

To queue something up for later delivery, your web method should add an item to the queue.

Each time the event handler fires, it peeks at the head of the queue for an item that need processing. If one is found, it removes it, processes it and repeats until its window has expired, the queue is empty or the head of the queue is not yet due.

like image 195
Nicholas Carey Avatar answered Dec 30 '25 14:12

Nicholas Carey


You can use the Thread.Sleep() method.

// Wait 5 seconds ...
Thread.Sleep(5000);

// Execute delayed code here.
like image 25
Joshua H Avatar answered Dec 30 '25 14:12

Joshua H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!