473,471 Members | 4,625 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

System.Threading.Timer interval in Windows Service

Hi Guys,

I am creating a Windows service that call a routine at given interval.
Once routine is complete, windows service should wait for 5 minutes and
then call the routine again. I was using System.Timers.Timer but i had
to remove it because of known bug(842739). Now i am using
System.Threading.Timer. It executes routine fine but the delay time is
sporadic, sometimes it executes routine after 5 minutes, sometimes 10
minuete, 13 minuntes. I want to wait exactly 5 mintes before it call
the routine. Here is my code snippet. I don't know how to fix it.
private Timer eventTimer;
private bool ProcessInProgress = false;

/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
TimerCallback eventCallBack = new TimerCallback(this.OnTimer);
eventTimer = new
Timer(eventCallBack,this,System.Threading.Timeout. Infinite,System.Threading.Timeout.Infinite);

//Here window service should wait for 5 mintes before call the routine
eventTimer.Change(300000,0);
}

public void OnTimer(Object source)
{
if(ProcessInProgress == false)
{
//RunTMService routine is called
RunTMService();

//Once RunTMService routine is complete, timer should wait for 5
more minutes and exeucte the routine again.
eventTimer.Change(300000,0);
}
}

private void RunTMService()
{
try
{
ProcessInProgress = true;
//Here perform all database activites and business logic
}
catch{}
finally
{
ProcessInProgress = false;
}
}

I don't understand why Timer does not exeute exactly after 5 minutes.
It is very sporadic. Any clue? Direction?

Nov 17 '05 #1
2 13154
Unfortunately, most timers like System.Threading.Thread.Sleep() are not very
precise as the time between triggers is dependant on a lot of things, so
having exact intervals can be extremely difficult.

Using timers, I would suggest dramatically decreasing the time and implement
some sort of check like checking the current time against time that your
worker function was last run (which you would have to note).

This way, if you’ve got your timer firing every say... 15 seconds, you are
far more likely to be woken nearer to your target time than you are with a 5
minute interval.

An improvement on this would be to move away from the timer completely and
implement it with a thread where you have a main loop, always looping with
the same logic as mentioned above, only if the condition is not met, a Sleep
call to cause the thread to sleep for a short period of time ( a matter of
seconds ideally) before checking again.

Brendan
"li***********@gmail.com" wrote:
Hi Guys,

I am creating a Windows service that call a routine at given interval.
Once routine is complete, windows service should wait for 5 minutes and
then call the routine again. I was using System.Timers.Timer but i had
to remove it because of known bug(842739). Now i am using
System.Threading.Timer. It executes routine fine but the delay time is
sporadic, sometimes it executes routine after 5 minutes, sometimes 10
minuete, 13 minuntes. I want to wait exactly 5 mintes before it call
the routine. Here is my code snippet. I don't know how to fix it.
private Timer eventTimer;
private bool ProcessInProgress = false;

/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
TimerCallback eventCallBack = new TimerCallback(this.OnTimer);
eventTimer = new
Timer(eventCallBack,this,System.Threading.Timeout. Infinite,System.Threading.Timeout.Infinite);

//Here window service should wait for 5 mintes before call the routine
eventTimer.Change(300000,0);
}

public void OnTimer(Object source)
{
if(ProcessInProgress == false)
{
//RunTMService routine is called
RunTMService();

//Once RunTMService routine is complete, timer should wait for 5
more minutes and exeucte the routine again.
eventTimer.Change(300000,0);
}
}

private void RunTMService()
{
try
{
ProcessInProgress = true;
//Here perform all database activites and business logic
}
catch{}
finally
{
ProcessInProgress = false;
}
}

I don't understand why Timer does not exeute exactly after 5 minutes.
It is very sporadic. Any clue? Direction?

Nov 17 '05 #2


"Brendan Grant" wrote:
Unfortunately, most timers like System.Threading.Thread.Sleep() are not very
precise as the time between triggers is dependant on a lot of things, so
having exact intervals can be extremely difficult.


That is true, but timers are can be trusted to be accurate within fractions
of a second, and certainly to not be out by seconds, or even minutes, as
indicated in the OP. I'd only hesitate to use a timer if the required
accuracy was greater than 100 ms (and there are timers for getting better
accuracy than that).

An error of 8 minutes is not due to the timers, but either the program
logic, or some deadly disturbance in the system.

I wrote this little console program to test the accuracy of
System.Threading.Timer. The first run, I set the timer interval to 1000 (ie.
1 sec), and it was typically being invoked with an accuracy of 0 to 60 ms
(mostly 0 - 30 ms). I did a second run, with an interval of 5 minutes, and
the accuracy was the same.

using System;
using System.Threading;

class TimerTest
{

static void Main()
{
TimerCallback timerDelegate = new TimerCallback(OnTimer);

// Create a timer to start immediately, and callback every 5
// minutes.
Timer timer = new Timer(timerDelegate, null, 0, 1000 * 60 * 5);

// Wait for ctrl-c to terminate this console app.
while (true)
{
};

}

static int count = 0;

static DateTime startTime = DateTime.Now;

// Timer callback
static void OnTimer(object state)
{
// Display the total time elapsed, in milliseconds,
// since we started.
TimeSpan span = DateTime.Now - startTime;
Console.WriteLine("Count = {0}, Time = {1}",count++,
span.TotalMilliseconds);
}
}

Output...

Count = 0, Time = 78.1245
Count = 1, Time = 300091.8294
Count = 2, Time = 600121.1592
Count = 3, Time = 900150.489
Count = 4, Time = 1200164.1939
Count = 5, Time = 1500193.5237
Count = 6, Time = 1800222.8535
Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: ELO | last post by:
Hi all Every week, I need to get two files on a remote server. I have developped a C# Windows Service with two System.Threading.Timer to do this task For the first one, the delay (TimeSpan...
3
by: Andy | last post by:
Hello. I want to use System.Threading.Timer to control when my windows form is invalidated. I want it to update at 60 frames per second. But, if I set the Interval of my timer to anything less than...
1
by: Can Balioglu | last post by:
Hi, I don't know if it's already known but I found a bug in System.Timers.Timer class. The 'Interval' property accepts a double which specifies the interval between two 'Elapsed' events. The...
3
by: Kenny | last post by:
I am running a windows service that takes actions based on a couple System.Threading.Timers. The intervals are usually short... based on the time of day, anywhere between 1 and 5 minutes. ...
4
by: Kürşat | last post by:
Hi all, I use System.Windows.Forms.Timer with a Windows service but nothing happens after given interval elapsed. It seems timer event does not occur. How can I use timers with Windows...
9
by: archana | last post by:
Hi all, I want to know about interval of timer. I am using timer in windows service.I head somewhere that when i set interval property of timer while setting interval, restart time of Pc is...
5
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the...
4
by: Lauren Quantrell | last post by:
I have just put together a vb.net app and now need to provide it to users. This application needs to run the code in a sub every 60 seconds from a Windows Service application. I have the...
8
by: Ollie Riches | last post by:
I'm looking into a production issue related to a windows service and System.Timers.Timer. The background is the windows service uses a System.Timers.Timer to periodically poll a directory location...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.