views:

557

answers:

3

I use the following code in a asp.net website.

On application init i call InitializeTimer() once.

The goal of the code was to run DoWork() once every hour (1 time per hour) .

I also wanted the code to execute on different time every loop so i added the random part.

The result i got was werid , i can not find a explaination why is happens.

The code executed the function after 2hrs , then again after 2hrs , then after 3hrs , then after 2hrs , and 2hrs again.**

Can anybody explain the reason?

using System.Timers;
....
private static random = new Random();
....
public static void InitializeTimer()
{
    tTimer = new Timer();
    tTimer.AutoReset = true;
    tTimer.Interval = TimeSpan.FromHours(1.0).TotalMilliseconds;
    tTimer.Elapsed += new ElapsedEventHandler(ClassName1.tMailer_Elapsed);
    tTimer.Start();
}

private static void tTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    tTimer.Interval += random.Next(-5, 5);

    DoWork();
}

Update:

  1. Please don't post "use windows service" , or "scheduled task". My question is for the following code I'm not looking for better alternatives. Also , during this test (10hrs) , website was with high traffic , iis pool did not restart!

  2. Based on the following MSDN: (http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx)

If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

Is it possible that re-setting the interval in the elapsed function is the cause of the problem?

Meaning that when tTimer_Elapsed function is called the count is 1hr(min a few millisecond) and my code "tTimer.Interval += random.Next(-5, 5);" is adding another full hour to the Interval?

+2  A: 

ASP.NET applications will get shut down when not in use. If someone hits your site, and then no more hits, it can get shut down. Your timer won't fire.

For this type of maintenance work you want to use a windows scheduled task or windows service.

Sam
thx for the input. the website or iis pool were NOT restarted during the test. i belive something is wrong with my code.
sharru
@sharru IIS recycles your application without user intervention.
Jader Dias
i aware of that , i log those events , no restart happened.
sharru
A: 

I second Sams suggestion of using windows scheduled task to hit a page every hour. I tried and tried to get mine to work and it sort of worked. I went to a scheduled task and it has never failed.

Steve
A: 

Check this out... Jeff Atwood actually discussed something similar. I guess it worked, but according to Jeff the site outgrew this method so they went to a dedicated task.

mpeterson