Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using System.Timers.Timer in asp.net

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?

like image 406
RuSh Avatar asked Feb 12 '10 22:02

RuSh


People also ask

Does system timers timer run in a separate thread?

Yes, they run in a different thread.

Is system threading timer thread safe?

Timer is not thread-safe.


1 Answers

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.

like image 163
Samuel Neff Avatar answered Oct 12 '22 20:10

Samuel Neff