Hello,
I have a little problem with a timer that I have set up. I use Thread.Sleep().
What I am trying to do, is to let a code run exactly when a new minute occurs on the millisecond (0 millisecond).
I have tried to set it up below and test it to write to file 4 times to see what the output is.
As seen the outputs are strange where the first result actually triggers on the 988:th millisecond before the next minute and the rest 4 milliseconds after the new minute.
//Minute,Second,Millisecond
32,59,988
34,0,4
35,0,4
36,0,4
Are there any better approach to do this to make it more accurate? I am not afraid to use microseconds in any
possible solution if that is a more accurate alternative.
static readonly object lockObject = new object();
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
FileStream hr = new FileStream("C:/test.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter file1 = new StreamWriter(hr); int count = 0;
DateTime dt = DateTime.Now; int sleepTime = 0;
while (true)
{
while (true)
{
Thread.Sleep(900);
//Sleep to exactly next minute on the millisecond
dt = DateTime.Now;
if (dt.Second >= 50)
{
sleepTime = 60000 - ((dt.Second * 1000) + dt.Millisecond);
Thread.Sleep(sleepTime); break;
}
}
lock (lockObject)
{
//We want this to react on the millisecond of the new minute
dt = DateTime.Now;
file1.WriteLine(dt.Minute + "," + dt.Second + "," + dt.Millisecond);
count++; if (count > 3) { break; }
}
}
file1.Close(); hr.Close();
}