Skip to content

Instantly share code, notes, and snippets.

@annymsMthd
Created May 13, 2015 03:40
Show Gist options
  • Save annymsMthd/b15678c9691e6baf6cae to your computer and use it in GitHub Desktop.
Save annymsMthd/b15678c9691e6baf6cae to your computer and use it in GitHub Desktop.
/// <summary>
/// Class Scheduler.
/// </summary>
public class ThreadPoolBasedScheduler : SchedulerBase, IDateTimeOffsetNowTimeProvider
{
protected override DateTimeOffset TimeNow { get { return DateTimeOffset.Now; } }
public override TimeSpan MonotonicClock { get { return Util.MonotonicClock.Elapsed; } }
public override TimeSpan HighResMonotonicClock { get { return Util.MonotonicClock.ElapsedHighRes; } }
protected override void InternalScheduleTellOnce(TimeSpan delay, ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
{
var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
InternalScheduleOnce(delay, () => receiver.Tell(message, sender), cancellationToken);
}
protected override void InternalScheduleTellRepeatedly(TimeSpan initialDelay, TimeSpan interval, ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
{
var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
InternalScheduleRepeatedly(initialDelay, interval, () => receiver.Tell(message, sender), cancellationToken);
}
protected override void InternalScheduleOnce(TimeSpan delay, Action action, ICancelable cancelable)
{
var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
InternalScheduleOnce(delay, action, cancellationToken);
}
protected override void InternalScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action, ICancelable cancelable)
{
var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
InternalScheduleRepeatedly(initialDelay, interval, action, cancellationToken);
}
private void InternalScheduleOnce(TimeSpan initialDelay, Action action, CancellationToken token)
{
var timer = new Timer(_ =>
{
if (token.IsCancellationRequested)
return;
action();
}, null, initialDelay, TimeSpan.FromMilliseconds(-1));
token.Register(timer.Dispose);
}
private void InternalScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action, CancellationToken token)
{
var timer = new Timer(_ =>
{
if (token.IsCancellationRequested)
return;
action();
}, null, initialDelay, interval);
token.Register(timer.Dispose);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment