473,568 Members | 2,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Timers out of sync?

I was originally using:

System.Windows. Forms.Timer

It started to lock my Window Service up, so I went to the next
evolution:

System.Threadin g.Timer

All was good. I was using it to send a message once a minute (to
another application on our network), logging to a text file each time
the message was sent (with a date / time stamp).

Then I noticed.. the time stamps in the log file were spacing out.
They would be at 1 minute intervals for a while, and then over time
they would gradually be something like 1 minute and 20 seconds.. 1
minute 27 seconds, etc. up until they were like several minutes apart.

I was confused at this point because I was under the impression that a
System.Threadin g.Timer ran in it's own environment and was independent
of anything else.

So I've been doing some research, at the simplist form I could conjure
up. I am now testing with:

using System.Timers;

Attempting to use 1 second intervals for testing purposes, the
resulting output is as follows:

09/24/2004 10:09:29.9687
09/24/2004 10:09:30.9687
09/24/2004 10:09:31.9687
09/24/2004 10:09:32.9687
09/24/2004 10:09:33.9687
09/24/2004 10:09:34.9687
09/24/2004 10:09:35.9687
09/24/2004 10:09:36.9687
09/24/2004 10:09:37.9843
09/24/2004 10:09:38.9843
09/24/2004 10:09:39.9843
09/24/2004 10:09:40.9843
09/24/2004 10:09:41.9843
09/24/2004 10:09:42.9843
09/24/2004 10:09:43.9843 <-- Notice Jump from 43 seconds to 45 on
next line
09/24/2004 10:09:45.0000
09/24/2004 10:09:46.0000
09/24/2004 10:09:47.0000
09/24/2004 10:09:48.0000
09/24/2004 10:09:49.0000
09/24/2004 10:09:50.0000
09/24/2004 10:09:51.0000
09/24/2004 10:09:52.0000
09/24/2004 10:09:53.0156
09/24/2004 10:09:54.0156
09/24/2004 10:09:55.0156
09/24/2004 10:09:56.0156
09/24/2004 10:09:57.0156
09/24/2004 10:09:58.0156
09/24/2004 10:09:59.0156
10/24/2004 10:10:00.0312

The following is the "snapTimer" DLL (A Visual Studio 2003 C# project)
that I use in this test:

using System;
using System.Diagnost ics;
using System.Timers;

namespace snapTimer
{
/// <summary>
/// Summary description for Timer.
/// </summary>

// A delegate type for hooking up change notifications.
public delegate void ElapsedEventHan dler(object sender, EventData e);

public class PlugIn : IDisposable
{
private static int _IntervalInSeco nds = 0;
private bool _Enabled = false;

private System.Timers.T imer watchDogTimer;

public event ElapsedEventHan dler Elapsed;

public PlugIn(int IntervalInSecon ds)
{
_IntervalInSeco nds = IntervalInSecon ds;
}

// Invoke the Changed event; called whenever list changes
protected virtual void OnElapsed(Event Data e)
{
if (Elapsed != null)
Elapsed(this, e);
}

private void EnableTimer()
{
watchDogTimer = new System.Timers.T imer(_IntervalI nSeconds * 1000);
watchDogTimer.A utoReset = true;

watchDogTimer.E lapsed -=new
System.Timers.E lapsedEventHand ler(watchDogTim er_Elapsed);
watchDogTimer.E lapsed +=new
System.Timers.E lapsedEventHand ler(watchDogTim er_Elapsed);
watchDogTimer.E nabled = true;
}

private void DisableTimer()
{
lock(this)
{
try
{
watchDogTimer.D ispose();
}
catch (Exception e1)
{
EventLog.WriteE ntry("snapTimer ", "Enabled = False\r\nError: " +
e1.ToString(), EventLogEntryTy pe.Error);
}
finally
{
watchDogTimer = null;
}
} // lock(this)
}

public bool Enabled
{
get { return _Enabled; }
set
{
_Enabled = value;

if (_Enabled) { EnableTimer(); }
else DisableTimer();
}
}

#region IDisposable Members

public void Dispose()
{
_Enabled = false; DisableTimer();
}

#endregion

private void watchDogTimer_E lapsed(object sender, ElapsedEventArg s
e)
{
OnElapsed(new EventData());
}
}
}
//
// EVENTDATA.CS - START
//

using System;

namespace snapTimer
{
/// <summary>
/// Summary description for EventData.
/// </summary>
public class EventData : EventArgs
{
private int SelectedRecID = 0;

public int RetID()
{
return SelectedRecID;
}
}
}

//
// EVENTDATA.CS - FINISH
//

The Windows Application I use for testing this, the following is the
segment of Code that deals with this Timer:

//
//
// START OF TEST SAMPLE CODE
//
//

private void cmdStart_Click( object sender, System.EventArg s e)
{
StartTimer();
}

private void StartTimer()
{
try
{
oTimer = new snapTimer.PlugI n(1);
oTimer.Elapsed -= new ElapsedEventHan dler(oTimer_Ela psed);
oTimer.Elapsed += new ElapsedEventHan dler(oTimer_Ela psed);
oTimer.Enabled = true;
}
catch (Exception e1)
{
MessageBox.Show ("Error: " + e1.ToString());
oTimer = null;
}
}

private void StopTimer()
{
try
{
if (oTimer != null)
{
oTimer.Elapsed -= new ElapsedEventHan dler(oTimer_Ela psed);
oTimer.Dispose( );
}
}
catch (Exception e1)
{
MessageBox.Show ("Error: " + e1.ToString());
}
finally
{
oTimer = null;

// Force garbage collection.
GC.Collect(GC.M axGeneration);
GC.WaitForPendi ngFinalizers();
}
}

private void cmdStop_Click(o bject sender, System.EventArg s e)
{
StopTimer();
}

private void oTimer_Elapsed( object sender, EventData e)
{
txtReport.Text +=
DateTime.Now.To String("mm/dd/yyyy hh:mm:ss.ffff") + "\r\n";

StopTimer();
StartTimer();

}

private void Form1_Closing(o bject sender,
System.Componen tModel.CancelEv entArgs e)
{
StopTimer();
}
//
//
// END OF TEST SAMPLE CODE
//
//

The Test Application is nothing more than 2 command buttons and a
textbox for dumping the Timestamp results to.

When the Timer is started, it hooks into an EventHandler that surfaces
an Event everytime the Timer elapses.

The Garbage Collection was an attempt to help clean up resources
during real time, because it appears every time I add an event handler
it just continues to leak memory. Even though when I terminate the
timer, I release the event handler the way I thought you were suppose
to.

I busted the "Timer" events into a separate DLL incase I needed to
tweak the settings for any reason.

Any feedback on how to better approach or handle this?
Nov 16 '05 #1
0 1743

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

Similar topics

1
371
by: GDumencu | last post by:
I have a C# program that have to run all the time. For some reasons I cannot make it a service. This program has 3 timers and by time to time ( days or weeks) one of them stops. Some times, starts working again after several hours. Each timer records a message to a file at the beginning and at the end of each timer. I can see the last...
0
1748
by: Dmitry Demchuk | last post by:
Hi everybody. Recently I ran into situation with System.Threading.Timer in my ASP.NET application. I reinstalled Windows on one of my servers and got timers stop firing events after while, they just stop functioning one-by-one. Here is detailed explanation. I run application on 2 dedicated Win 2003 servers. Server A serves about 1000 active...
2
1526
by: news.eclipse.co.uk | last post by:
Hi - I have two seperate threads each running timers - I was wondering if there is any way to sync the two seperate timers using a system clock or something - or would I have to simply create a routine? - which would not be that difficult I realize but was wondering - cheers James Jenkins www.tamarsolutions.co.uk
9
7850
by: Mark Rae | last post by:
Hi, I've seen several articles about using System Timers in ASP.NET solutions, specifically setting them up in Global.asax' Application_OnStart event. I'm thinking about the scenario where I might need to carry out some back-end processing without pausing the individual users' Session while that process runs. E.g. I might provide the...
3
354
by: Maarten | last post by:
Hi In my aplication it seems that my timer slows down everything, is there a better and/or diferent way than using a timer Maarten
1
1815
by: | last post by:
Frustrated.. (I have seen other posts regarding this problem with no resolution..) I am using dotnet 1.1 with latest SP on a Win2KP box (actually 2 boxes), have even run the service on WinXP SP2 box.. I have created a service to grab data off a receive socket (small packets), place in a queue (Queue class), and do an insert into SQL. I have 3...
1
3026
by: Jonathan Woods | last post by:
Hi there, I have three methods these need to execute at every interval time. I would like to know which option is better? Option A) Three System.Timers.Timer objects these execute each method. timer1.Elapsed += new System.Timers.ElapsedEventHandler(Method1_Elapsed);
5
12197
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...
0
884
by: bubbha70 | last post by:
Will a Timer keep my web service alive? The reason I ask is, I have a disconnected dataset cached at the web service tier. Any changes (inserts, updates and deletes) only alters the dataset. I use the Timer / TimerCallback to trigger a method that executes the various DataAdapter.Update to sync any changes to it's respective tables in the...
1
7660
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...
0
7962
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...
0
6275
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...
1
5498
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...
0
5217
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...
0
3651
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2101
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
0
932
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.