Emaad Shehzzad
Emaad Shehzzad

Reputation: 35

Correct usage of Timer in a C# webapplication

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

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Correct way to use Timer in WebAplication is not to use timers at all.

Alternative approaches for long running/repeating tasks:

  • scheduled tasks on server side (external process with Windows or any other scheduling tools).
  • ping data with script scheduled to run repeatedly
  • re-request data from client browser (assuming it is opened all the time)
  • use cache and configure items to re-request on expiration.

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

cheft
cheft

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

Related Questions