Last active
May 17, 2018 08:58
-
-
Save jonny-novikov/628452a6806232cfa5fc4f4f0db641cd to your computer and use it in GitHub Desktop.
Run task in periodic manner
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
RunPeriodicAsync(() => { Console.WriteLine("Tick once a minute!"); }, TimeSpan.Zero, TimeSpan.FromMinutes(1), default(CancellationToken)); |
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
/// <summary> | |
/// The `onTick` method will be called periodically unless cancelled. | |
/// </summary> | |
/// <param name="onTick"></param> | |
/// <param name="dueTime"></param> | |
/// <param name="interval"></param> | |
/// <param name="token"></param> | |
/// <returns></returns> | |
private static async Task RunPeriodicAsync(Action onTick, TimeSpan dueTime, TimeSpan interval, CancellationToken token) | |
{ | |
// Initial wait time before we begin the periodic loop. | |
if (dueTime > TimeSpan.Zero) | |
{ | |
await Task.Delay(dueTime, token); | |
} | |
// Repeat this loop until cancelled. | |
while (!token.IsCancellationRequested) | |
{ | |
// Call our onTick function. | |
onTick?.Invoke(); | |
// Wait to repeat again. | |
if (interval > TimeSpan.Zero) | |
{ | |
await Task.Delay(interval, token); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment