SystemClockTimer.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Threading;
  3. namespace DesktopClock;
  4. /// <summary>
  5. /// A timer that syncs with the system clock.
  6. /// </summary>
  7. public sealed class SystemClockTimer : IDisposable
  8. {
  9. private readonly Timer _timer;
  10. public SystemClockTimer()
  11. {
  12. _timer = new Timer(_ => OnTick());
  13. }
  14. /// <summary>
  15. /// Occurs after the second changes on the system clock.
  16. /// </summary>
  17. public event EventHandler SecondChanged;
  18. /// <summary>
  19. /// Number of milliseconds until the next second on the system clock.
  20. /// </summary>
  21. private int MillisecondsUntilNextSecond => 1000 - DateTimeOffset.Now.Millisecond;
  22. /// <summary>
  23. /// <inheritdoc/>
  24. /// </summary>
  25. public void Dispose() => _timer.Dispose();
  26. /// <summary>
  27. /// Schedules the timer to start on the next second that elapses.
  28. /// </summary>
  29. public void Start() => ScheduleTickForNextSecond();
  30. /// <summary>
  31. /// Immediately stops the timer.
  32. /// </summary>
  33. public void Stop() => _timer.Change(Timeout.Infinite, Timeout.Infinite);
  34. private void OnTick()
  35. {
  36. ScheduleTickForNextSecond();
  37. SecondChanged?.Invoke(this, EventArgs.Empty);
  38. }
  39. /// <summary>
  40. /// Starts the timer and schedules the tick for the next second on the system clock.
  41. /// </summary>
  42. private void ScheduleTickForNextSecond() =>
  43. _timer.Change(MillisecondsUntilNextSecond, Timeout.Infinite);
  44. }