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

5 Comments

  • Can you please add some clarity to the comment " When your background thread throw and exception the working process will shout down! and IIS will recycle and start again so be careful."

    Specifically:

    - Are you saying that the whole web application would be shut down and restarted or that method being executed by the timer would stop and then the timer would restart?

    - Will this exception shut down IIS or just my web application?

    Again, please provide some specifics about the exception recycling IIS and maybe a link on where this can be researched more if you have it.

    Great article. Thanks!

  • yes Drew;
    when any excpetion occur from the background timer thread your application will restart and recycle again. just the application which the thread is working on.
    you may check here for more information

    http://petesbloggerama.blogspot.com/2008/12/iis-aspnet-recycling-deadlock-detected.html

    http://support.microsoft.com/?id=911816

    http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.aspnet/2007-01/msg00753.html

    Not: I found out the problem by accident when our clients start to losse there session state.
    hope this helps

  • HI YOUNIS,

    I am using System.Threading.Timer for running a windows service.

    I am using following Code:

    -----------------------------------------

    Dim oCallBack As New TimerCallback(AddressOf OnTimedEvent)

    oTimer = New System.Threading.Timer(oCallBack, Nothing, 9000, 9000)

    Private Sub OnTimedEvent(ByVal state As Object)

          // Start Process

    ---------------------------------------------

    Now my problem is before one thread of time is completed another is called.

    However, I want  the next thread to start only if the previous one has ended..

    I think  I am supposed to use Join function.

    But have not clue how to use it in this scenario.

    Thanks

    Gourav

       End Sub

  • I get this error when I use this code. CheckDailyTests() is a method that I call within CheckData. As follows:
    private static void CheckData(object sender)
    {
      CheckDailyTests();
    }
    An object reference is required for the non-static field, method, or property 'DP_Liabrary.DP_BusinessComponent.TimerStarter.CheckDailyTests()'
    Could you please help? :-)

  • Hi JuniorWebDeveloper ;
    i think that you are trying to refrance some nonstatic member with a static method ! please check the post below;
    social.msdn.microsoft.com/.../c54db21c-3330-4dbf-a29f-d40bd6db3fd6

Comments have been disabled for this content.