Execute method in global.asax every few minutes

14,746

You could have a timer in the Application_Start of the Global.asax, but this is not very flexible since you need to do a request to the application for the timer to start. There are dangers to doing it this way though, as detailed by Haacked:

A better way of doing it is to have a web service that acts as an interface to your ASP.NET application and have a windows service that calls your web service on scheduled intervals:

More details here:

Share:
14,746
carlbenson
Author by

carlbenson

Updated on June 04, 2022

Comments

  • carlbenson
    carlbenson almost 2 years

    What is the most effective way to execute a method in the Global.asax file every x number of minutes? Is there a way to have the ASP.NET server run a background thread that fires a tick event after a certain elapsed period?

  • Chris Gessler
    Chris Gessler almost 12 years
    You beat me by 22 seconds, but I actually typed something :)
  • Chris Sinclair
    Chris Sinclair almost 12 years
    If you do not have access to your server (say it's hosted by a third party) and cannot install Windows services, then you can fake one using the ASP.NET cache: codeproject.com/Articles/12117/…
  • carlbenson
    carlbenson almost 12 years
    In my particular case, I am okay with requiring a request to be made for the application to start. Your web service idea is great though, and definitely a more appropriate answer for generic cases of my question. Thanks a lot!
  • Moiz Tankiwala
    Moiz Tankiwala almost 11 years
    Not a very good idea. An ASP.Net application may have been shut down (typically the configuration of hosted web servers, where application is shut down after a period of inactivity and only started on receiving a new request).
  • Fandango68
    Fandango68 about 7 years
    @ChrisSinclair is 100% spot on. You should not be developing, with the mindset that you have full access to company resources or client resources. Everything should be portable and expandable, and hence a ASP.net cached solution is really the only way to go.
  • Fandango68
    Fandango68 about 7 years
    @MoizTankiwala is correct. Not a good idea. Most web services have a timeout, which you may not have control over. Web servers may crash. Then what!? You may need to host your ASP.net page on a remote service that at least gives some gaurantees it won't stop - cloud, etc. Try to avoid using server internals to do the job. Use the cache!