Windows Service and DateTime issue

  • Thread starter Thread starter PurpleServerMonkey
  • Start date Start date
P

PurpleServerMonkey

Hopefully a simple DateTime problem.

I've got a windows service created in C# on .Net Framework 2.0, the
service uses a system timer to fire an event every second and compare
that against a known time to fire off a worker thread. All the
DateTime objects are using local time as the services are local to the
server.

DateTime runAt = DateTime.Parse("4/24/2007 2:30:00 PM");
System.Timers.Timer _timer = new System.Timers.Timer();

protected override void OnStart(string[] args)
{
base.OnStart(args);
_timer.Interval = 1000;
_timer.Elapsed += new ElapsedEventHandler(timeElapsed);
_timer.Start();
}

void timeElapsed(object sender, ElapsedEventArgs args)
{
if (DateTime.Compare(runAt, DateTime.Now) ==
0)
{
// Spawn a new thread to do the cleanup
work
WorkerThread threadObj = new WorkerThread();
Thread workerThread = new Thread(new
ThreadStart(threadObj.BeginTask));
workerThread.Start();
}
}

The problem is that the DateTime.Compare never says that the two
DateTime objects match so the worker thread isn't created. I've
confirmed that the formats of the two datetime formats are the same
using an Event Log entry and they match perfectly.

Any ideas to why this happening are greatly appreciated.
 
I've
confirmed that the formats of the two datetime formats are the same
using an Event Log entry and they match perfectly.
OK; DateTime doesn't *have* a format - it is just an integer
internally. It is only when you make a string out of it that this
kicks in. I would be *astonished* if 2 DateTimes ever matched in this
scenario; they will always be off by (at least) a few ms.

Presumably you would reset runAt after running (moving it forward)? In
which case the simplest solution is to use "runAfter" - and just run
it the first time you go past the limit. Additionally, note that
Elapsed may be firing on a different thread already, so you might want
to watch out for thread-safety, especially regarding the "runAt" /
"runAfter" variable (only an issue if you also change this var from
another thread).

Marc
 
OK; DateTime doesn't *have* a format - it is just an integer
internally. It is only when you make a string out of it that this
kicks in. I would be *astonished* if 2 DateTimes ever matched in this
scenario; they will always be off by (at least) a few ms.

Presumably you would reset runAt after running (moving it forward)? In
which case the simplest solution is to use "runAfter" - and just run
it the first time you go past the limit. Additionally, note that
Elapsed may be firing on a different thread already, so you might want
to watch out for thread-safety, especially regarding the "runAt" /
"runAfter" variable (only an issue if you also change this var from
another thread).

Marc

Thanks Marc, that makes a lot of sense.
 
Back
Top