Skip to content

Instantly share code, notes, and snippets.

@jonny-novikov
Last active May 17, 2018 08:58
Show Gist options
  • Save jonny-novikov/628452a6806232cfa5fc4f4f0db641cd to your computer and use it in GitHub Desktop.
Save jonny-novikov/628452a6806232cfa5fc4f4f0db641cd to your computer and use it in GitHub Desktop.
Run task in periodic manner
RunPeriodicAsync(() => { Console.WriteLine("Tick once a minute!"); }, TimeSpan.Zero, TimeSpan.FromMinutes(1), default(CancellationToken));
/// <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