Global Timer (Background Timer)
Updated on 01.19.2009
Why do you need a Global Timer ?
There are many reason that you might want to use a global timer for, like pulling data from you database on time periods to prevent user from displaying empty data. I used the global timer to get signed up online users data ( like online user count, cities and assigned rules).
there are 3 types of timer class in ASP.NET;
Here i will not discus the deference between the above timer class (you may check the links and read msdn about them)but I'll show how to use System.Threading.Timer to create a background timer.
the time that I’ll create in this article will be created once and will keep working as long as my web application keep working. If the application stopped for any reason the timer will start again with the application restart.
First of all create a class that will star Threading.Timer, make sure to create the timer starter method as Static method because we’ll call that method from Global.asax applicathin start method. Make the class as below;
Add using System.Threading; as reference;
1: public class TimerStarter
2: {
3: private static Timer threadingTimer;
4:
5: public static void StartTimer()
6: {
7: if (null == threadingTimer)
8: {
9: threadingTimer = new Timer(new TimerCallback(CheckData),
HttpContext.Current, 0, 600000);
10: }
11: }
12: private static void CheckData(object sender)
13: {
14: //ToDo check Data
15: }
16: }
Now Let me explain the code above; I declared a threadingTimer but did not initialize it. The main method here is StartTimer; Its a static method. The method checks if the threadingTimer Object is null or not. If its the first time that the method is called the threadingTimer will be null and will be created. line 9 creates and sets the timer object. TimerCallback is the delegate that will be called within timer intervals, here I call CheckData Method. CheckData method must be overloaded to match TimerCallback delegate. HttpContext.Curent is the object that will be used by the callback method; if you do not need any extra information for your method you can pass it as null. the 0 (zero) force the threadingtimer to call CheckData method as soon as the timer is created. You may set any milliseconds you want the timer to wait and call CheckData method. 600000 tells the timer to call CheckData method every 10 min. Call your timer from Global.asax as below;
1: void Application_Start(object sender, EventArgs e)
2: {
3: TimerStarter.StartTimer();
4: }
UPDATE : When your background thread throw and exception the working process will shout down! and IIS will recycle and start again so be careful.
That is all!
You may use System.Timers.Timer in a deferent way to achieve the same goal. Check MSDN for more details.
Hope this Helps