In a C# (.NET 4.0) Application, I use the Reactive Extensions (2.0.20823.0) to generate time boundaries for grouping events into aggregate values. To simplify queries to the resulting database, these boundaries need to be aligned on full hours (or seconds in the example below).
Using Observable.Timer()
:
var time = DefaultScheduler.Instance;
var start = new DateTimeOffset(time.Now.DateTime, time.Now.Offset);
var span = TimeSpan.FromSeconds(1);
start -= TimeSpan.FromTicks(start.Ticks % 10000000);
start += span;
var boundary = Observable.Timer(start, span, time);
boundary.Select(i => start + TimeSpan.FromSeconds(i * span.TotalSeconds))
.Subscribe(t => Console.WriteLine("ideal: " + t.ToString("HH:mm:ss.fff")));
boundary.Select(i => time.Now)
.Subscribe(t => Console.WriteLine("actual: " + t.ToString("HH:mm:ss.fff")));
You can see that the intended and the actual time of the timer ticks drift apart quite heavily:
ideal: 10:06:40.000
actual: 10:06:40.034
actual: 10:06:41.048
ideal: 10:06:41.000
actual: 10:06:42.055
ideal: 10:06:42.000
ideal: 10:06:43.000
actual: 10:06:43.067
actual: 10:06:44.081
ideal: 10:06:44.000
ideal: 10:06:45.000
actual: 10:06:45.095
actual: 10:06:46.109
ideal: 10:06:46.000
ideal: 10:06:47.000
actual: 10:06:47.123
actual: 10:06:48.137
ideal: 10:06:48.000
...
I also make use of a HistoricalScheduler
and of course I have no problems there. I can tolerate slight inaccuracies and I do not need to care about system clock changes. There are no heavyweight operations triggered by those Observables.
Also, I know there is a lengthy discussion of RX timer drift problems in this blog post, but I don′t seem to be able to wrap my head around it.
What would be the right way to periodically schedule an Observable
without systematic timer drift?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…