473,748 Members | 2,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

System.Threadin g.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.T imer but i had
to remove it because of known bug(842739). Now i am using
System.Threadin g.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 ProcessInProgre ss = 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(t his.OnTimer);
eventTimer = new
Timer(eventCall Back,this,Syste m.Threading.Tim eout.Infinite,S ystem.Threading .Timeout.Infini te);

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

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

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

private void RunTMService()
{
try
{
ProcessInProgre ss = true;
//Here perform all database activites and business logic
}
catch{}
finally
{
ProcessInProgre ss = 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 13212
Unfortunately, most timers like System.Threadin g.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.T imer but i had
to remove it because of known bug(842739). Now i am using
System.Threadin g.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 ProcessInProgre ss = 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(t his.OnTimer);
eventTimer = new
Timer(eventCall Back,this,Syste m.Threading.Tim eout.Infinite,S ystem.Threading .Timeout.Infini te);

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

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

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

private void RunTMService()
{
try
{
ProcessInProgre ss = true;
//Here perform all database activites and business logic
}
catch{}
finally
{
ProcessInProgre ss = 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.Threadin g.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.Threadin g.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.Threadin g;

class TimerTest
{

static void Main()
{
TimerCallback timerDelegate = new TimerCallback(O nTimer);

// Create a timer to start immediately, and callback every 5
// minutes.
Timer timer = new Timer(timerDele gate, 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.WriteLi ne("Count = {0}, Time = {1}",count++,
span.TotalMilli seconds);
}
}

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
5604
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 dueTime) is always set to 6 days, 23 hours, 59 minutes, .. Some weeks ?!?, the timer restarts immediately after its execution (and loop indefinitely). I have made a lot of tests and this issue does not occur with a delay < 1 day .. Any suggestion
3
3317
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 30ms, the event isn't triggered. That means I am stuck in the neighborhood of 30 frames per second. The reason why I am doing this at all is because when I tried to Invalidate my form from with in the OnPaint call, other windows suddenly...
1
7721
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 'Start' method just sets the 'Enabled' property to true. And the problem lies in the 'Enabled' property. It casts the interval value to an integer and calls the constructor of the System.Threading.Timer class which only accepts a non-negative...
3
2336
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. Recently however, the event that was firing based on the timer started firing rapidly; it fired about 9000 times in a minute and a half. After the minute and a half was up, it returned to normal behavior! .... just wondering if anyone has experienced...
4
3174
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 Services? Thanks in advance.
9
2644
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 consider. My question is if i am using timer in my windows service, is there any place where interval related information like interval set used by my
5
12245
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 event handlers may take longer than the interval for either of the timers, so it's possible for multiple events to fire "simultaneously" and for events to queue up. I'm attempting to get the timers to sync on some reference type object, or use...
4
14404
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 functionality of the sub working fine but I cannot figure out how to run the timer. The sub DoSomethingHere() needs to run every 60 seconds. It doesn't need to change the interval or anything like that. It just needs to run every 60 seconds as long as...
8
3370
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 on a network for files and then copies these files to another location (on the network) AND then updates a record in the database. The file copying is performed before the database update because the file system is not transactional. The code...
0
8822
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9528
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9310
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9236
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8235
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6792
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3298
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 we have to send another system
2
2774
muto222
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.