Skip to content

Instantly share code, notes, and snippets.

@maxfridbe
Created December 21, 2012 20:31
Show Gist options
  • Save maxfridbe/4355598 to your computer and use it in GitHub Desktop.
Save maxfridbe/4355598 to your computer and use it in GitHub Desktop.
periodically run task with cancellation input
//original http://stackoverflow.com/a/7472334/518
var cancellationTokenSource = new CancellationTokenSource();
var task = Repeat.Interval(
TimeSpan.FromSeconds(15),
() => CheckDatabaseForNewReports(), cancellationTokenSource.Token);
internal static class Repeat
{
public static Task Interval(
TimeSpan pollInterval,
Action action,
CancellationToken token)
{
// We don't use Observable.Interval:
// If we block, the values start bunching up behind each other.
return Task.Factory.StartNew(
() =>
{
for (;;)
{
if (token.WaitCancellationRequested(pollInterval))
break;
action();
}
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
static class CancellationTokenExtensions
{
public static bool WaitCancellationRequested(
this CancellationToken token,
TimeSpan timeout)
{
return token.WaitHandle.WaitOne(timeout);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment