Reputation: 35
I have been looking extensively for examples on how to correctly use the timer feature in C# to trigger a function. The function here which is called GetIntStatus() basically aggregates data from several databases and stores in a seperate database. I need to run this function in a interval of every 2 hours to refresh the data and then that data will be pulled into a grid (this part I have it covered). Can someone show me how best to handle this situation ?
Upvotes: 0
Views: 102
Reputation: 100527
Correct way to use Timer
in WebAplication is not to use timers at all.
Alternative approaches for long running/repeating tasks:
Sometimes it is ok to use short-lived timers to handle timeouts during request. I.e. Task.Delay
may be used to force timeout when run in parallel with some other potentially long task.
Upvotes: 3
Reputation: 152
Not totally sure how GetIntStatus() is implemented but I had to do something similar. Basically, you just start a timer, set an interval, and set some method to get called when the interval has elapsed.
Here's the syntax:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Start();
timer.Interval = 5 * 60 * 1000; // 5 minute updates
timer.Elapsed += (sender, args) => PerformUpdates();
In my case, the PefromUpdates() was an async method that returned a Task.
Upvotes: 0