Quantcast
Viewing latest article 4
Browse Latest Browse All 9

C# Thread.Sleep(TimeSpan) to Run Every 10 minutes

Based on truncating a DateTime to the second in C# while preserving the “Kind” (Local, UTC, Undefined):

dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));

Thread.Sleep until the next 10 minute mark (e.g. Run every 00, 10, 20, 30, 40, 50 minutes):

Thread.Sleep(
    TimeSpan.FromTicks(
        (TimeSpan.TicksPerMinute * 10) - 
        (DateTime.Now.Ticks % (TimeSpan.TicksPerMinute * 10))
    )
);

Credit: http://stackoverflow.com/a/1005222/152852

In the real world, the above code appears to be waking up a fraction of a second too early. So perhaps adding an additional tick might be the way to go:

Thread.Sleep(
    TimeSpan.FromTicks(
        1 + (TimeSpan.TicksPerMinute * 10) - 
        (DateTime.Now.Ticks % (TimeSpan.TicksPerMinute * 10))
    )
);

Viewing latest article 4
Browse Latest Browse All 9

Trending Articles