Wednesday, May 30, 2012

Scheduled Tasks in ASP.NET Web Applications using Timers

I'm just found a article that I found on the MSDN blog. And I've just decieded to share on my blog with more explantation.

Before I found this, I honestly had known that the scheduled tasks can be only running on window scheduler tasks.

I had even tried to use Threading with looping to avoid window scheduler tasks on my web application.

Finally, I just found this article .

Scenario:
A Web app calls wcf services every one minute. As I'm MVC web developer, my web app is always MVC application.
System timer In global.asax, you need to create a Timers method. In below example, I give timer method name to ServiceTimers.

1: privatevoid ServiceTimers()

2: {

3: System.Timers.Timer serivceTimer = new System.Timers.Timer();

4: serivceTimer.Enabled = true;

5: serivceTimer.Interval = (60000); // one minute

6:

7: serivceTimer.Elapsed += new

8: System.Timers.ElapsedEventHandler(ServiceTimer_Elaspsed);

9: }

Within the method, the last line is obviously event handler which call to a event which contains Web service called.