Permalink
Browse files

Attempting a rewrite of DateTimePrecise for issue #66 and #48

  • Loading branch information...
nberardi committed Sep 21, 2012
1 parent 939d02e commit 50617a713ad1d5eb1bfb8c2a46db519d47bfcb03
Showing with 64 additions and 0 deletions.
  1. +1 −0 src/FluentCassandra.csproj
  2. +63 −0 src/System/DateTimePrecise.cs
@@ -217,6 +217,7 @@
<Compile Include="Operations\Void.cs">
<SubType>Code</SubType>
</Compile>
+ <Compile Include="System\DateTimePrecise.cs" />
<Compile Include="Thrift\Collections\THashSet.cs" />
<Compile Include="Thrift\Protocol\TBase.cs" />
<Compile Include="Thrift\Protocol\TBase64Utils.cs" />
@@ -0,0 +1,63 @@
+using System;
+using System.Diagnostics;
+using System.Linq;
+
+namespace System
+{
+ public class DateTimePrecise
+ {
+ private static readonly DateTimePrecise Instance = new DateTimePrecise(10);
+
+ public static DateTime Now
+ {
+ get { return Instance.GetUtcNow().LocalDateTime; }
+ }
+
+ public static DateTime UtcNow
+ {
+ get { return Instance.GetUtcNow().UtcDateTime; }
+ }
+
+ public static DateTimeOffset NowOffset
+ {
+ get { return Instance.GetUtcNow().ToLocalTime(); }
+ }
+
+ public static DateTimeOffset UtcNowOffset
+ {
+ get { return Instance.GetUtcNow(); }
+ }
+
+ private readonly double _syncSeconds;
+ private readonly Stopwatch _stopwatch;
+ private DateTimeOffset _baseTime;
+
+ public DateTimePrecise(int syncSeconds)
+ {
+ _syncSeconds = syncSeconds;
+ _stopwatch = new Stopwatch();
+
+ Syncronize();
+ }
+
+ private void Syncronize()
+ {
+ lock (_stopwatch) {
+ _baseTime = DateTimeOffset.UtcNow;
+ _stopwatch.Restart();
+ }
+ }
+
+ public DateTimeOffset GetUtcNow()
+ {
+ var elapsedSeconds = _stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
+
+ if (elapsedSeconds > _syncSeconds) {
+ Syncronize();
+ return _baseTime;
+ }
+
+ return _baseTime.AddSeconds(elapsedSeconds);
+ }
+ }
+}

0 comments on commit 50617a7

Please sign in to comment.