In my project I would like to be able to call a method after 3 minutes have passed. There is no \"main loop\" to speak of so I cannot use a stopwatch and constantly check if
After trying out several options, the method was not self-triggering. Hence, I used Javascript to solve the same problem as shown below.
<script>
function Timer() {
$.ajax({
url: "@Url.Action("Timer", "Exam")",//Method to call. Timer Method in Exam Controller
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
cache: false,
async: true
});
}
setInterval(function () { Timer(); }, 5000);//Triggers method Timer() after 5 seconds
</script>
I really believe your idea with the Timer
object is the right way to go. It sounds like you're familiar with how to use it - but here's an example:
aTimer = new System.Timers.Timer(1000 * 60 * 3);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Use a Timer.
While there will be a slight overhead if you create a 1000 timers, it won't be too much. Timers will do their job and fire an event when 3 minutes have passed. Also, if you want your code to repeat every 3 minutes, Timers are the way to go.
Timer is not a good solution for hundreds/thousands, as Timers are a limited resource.
Are all the methods to be called from the same application?
If so, I would create a small stub class that had a datetime, and an Action, and add delegates to the method to be called, along with the target time. Then in a background thread loop through the list and call the delegates when appropriate (and remove them obviously)
An alternate solution would be to do something like QueueUserWorkItem for each method to be called, and first thing in the thread sleep for the appropriate amount of time until the method should be called.
For all solutions (mine and others), be aware of any marshaling you have to do if you are interacting with the GUI, or any locking that may need to be done to avoid threading concurrency issues
if you have hundreds or thousand of those timers, some scheduling will do the job.
You really should investigate quartznet
lots of concurrent timers perform not very well as i experienced, quartznet will do.
and if you really want to have those scheduling tasks in your application, perhaps this article gives you some ideas Task Scheduler Class Library for .NET