-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Syncing with system clock looks nicer when the app is next to it.
- Loading branch information
1 parent
993236b
commit 036ca89
Showing
4 changed files
with
66 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
using System; | ||
using System.Threading; | ||
|
||
namespace Network_Monitor; | ||
|
||
/// <summary> | ||
/// A timer that is synced with the system clock. | ||
/// </summary> | ||
/// <remarks> | ||
/// <see href="https://github.com/danielchalmers/DesktopClock" /> | ||
/// </remarks> | ||
public sealed class SystemClockTimer : IDisposable | ||
{ | ||
private readonly Timer _timer; | ||
|
||
public SystemClockTimer() | ||
{ | ||
_timer = new Timer(_ => OnTick()); | ||
} | ||
|
||
/// <summary> | ||
/// Occurs after the second of the system clock changes. | ||
/// </summary> | ||
public event EventHandler SecondChanged; | ||
|
||
/// <summary> | ||
/// Number of milliseconds until the next second on the system clock. | ||
/// </summary> | ||
private int MillisecondsUntilNextSecond => 1000 - DateTimeOffset.Now.Millisecond; | ||
|
||
public void Dispose() => _timer.Dispose(); | ||
|
||
public void Start() => ScheduleTickForNextSecond(); | ||
|
||
public void Stop() => _timer.Change(Timeout.Infinite, Timeout.Infinite); | ||
|
||
private void OnTick() | ||
{ | ||
ScheduleTickForNextSecond(); | ||
|
||
SecondChanged?.Invoke(this, EventArgs.Empty); | ||
} | ||
|
||
/// <summary> | ||
/// Starts the timer and schedules the tick for the next second on the system clock. | ||
/// </summary> | ||
private void ScheduleTickForNextSecond() => | ||
_timer.Change(MillisecondsUntilNextSecond, Timeout.Infinite); | ||
} |