Repository navigation
Clocks
- The Clock class
- Overriding the current date and time
- Built-in Clock implementations
- Implement a custom clock
Every .NET application uses the current date and/or time in one way or another. The .NET Framework provides the DateTime and younger DateTimeOffset structures for this. Their static .Now and .UtcNow properties allow us to obtain the date and time of the current machine, which can then be used as a timestamp, for example, or to perform some other time-based calculation as part of your business logic.
However, the problem with directly calling these methods in your code is that it becomes hard to control (e.g. mock or stub) the current system's time in automated tests. Being able to control time as well as any other IO-related dependency in your tests can be crucial, especially if your business logic is based on very specific time-related events.
For this reason, the Kingo framework contains the Clock class. The Clock class can be used to obtain the current date and time through it static Clock.Current property:
var currentDateAndTime = Clock.Current.LocalDateAndTime();The Clock.Current property actually returns an instance of the IClock interface, which in turn contains all methods necessary to read the current date and time for the local time zone or in UTC time - just like the .Now and .UtcNow properties of the DateTimeOffset structure. In fact, by default, the IClock instance returned will simply use these properties to obtain the current date and time values for you. (Note that the IClock type work with DateTimeOffset instances only, since that's now the recommended DateTime-structure in the .NET Framework. You can convert these instances back to DateTime values if your code still depends on them.)
The beauty of the Clock class is that is provides two methods to override the current clock by providing you own IClock-instance: Clock.Override(IClock) and Clock.OverrideAsyncLocal(IClock). Both methods returns an instance of the IDisposable class representing a scope in which the specified clock will be active:
using (Clock.Override(clockToUse))
{
// Current date and time has now changed on any thread.
var currentDateAndTime = Clock.Current.LocalDateAndTime();
}
using (Clock.OverrideAsyncLocal(clockToUse))
{
// Current date and time has now changed on threads that share the current LogicalCallContext.
var currentDateAndTime = Clock.Current.LocalDateAndTime();
}
using (Clock.OverrideThreadLocal(clockToUse))
{
// Current date and time has now changed on the current thread only.
var currentDateAndTime = Clock.Current.LocalDateAndTime();
}The first method behaves somewhat like a static override: each and every thread in the current AppDomain will now obtain the current date and time based on the instance you have provided. This can useful if you want your application to use a different clock that the default one for its entire lifetime.
The second method, OverrideAsyncLocal(IClock), will also override the current clock, but only for threads that share the current LogicalCallContext. This is particularly handy for controlling time in Unit Tests, where each test may run on it's own thread and you don't want these tests to interfere with each other. Because the clock is bound to the LogicalCallContext, the clock remain visible/accessible to all threads that participate in the async/await flow (assuming you don't use ConfigureAwait(false)).
The third and final way to set the current clock is to use the OverrideThreadLocal(IClock) method. As its name suggests, this will only set the clock on the current thread. Its use is similar to that of the OverrideAsyncLocal(IClock) counterpart, but is slightly cheaper in its use because you prevent the overhead of copying the clock's reference from one ExecutionContext to another, which is better avoided if you don't need it.
It is worth mentioning here that all OverrideXyz(IClock) methods can be nested and that Clock.Current will return the value of whatever scope is active at that time. For more on how scopes can be nested we refer to the Context<T> on which the Clock class is based.
The framework provides several built-in clocks that can be used for different purposes.
Naturally, the framework contains a default IClock-implementation, accessible through the static Clock.Default property. This is the instance that is returned by Clock.Current if it is not overridden by a custom implementation.
Another clock that you can use is the DelegateClock. This is a Clock implementation which takes a Func<DateTimeOffset> through its constructor that will returns that clock's UTC date and time. Basically, the DelegateClock can be used in unit tests, for example, where you want to return the current time using a delegate or private method in your unit test class without the need to implement your own Clock class in the process. Moreover, as of version 2.0.6, the Clock class provides OverrideXyz(Func<DateTimeOffset>) methods so that you can override the current system time using a delegate immediately.
Another clock that may be helpful in unit tests is the StopwatchClock. The StopwatchClock accepts a certain point in time in its constructor, which will serve as its start time. You can then start and stop this clock as you like through its .Start() and .Stop() methods.
// Set the start date of this clock the January 1st, 2000, UTC Time.
var clockToUse = new StopwatchClock(new DateTimeOffset(2000, 1, 1, 8, 10, 34, TimeSpan.Zero));
clockToUse.Start();
using (Clock.OverrideAsyncLocal(clockToUse))
{
// Local time is now around the year 2000, depending on the current time zone.
var currentDateAndTime = Clock.Current.LocalDateAndTime();
}
clockToUse.Stop();As the name suggests, this clock uses the Stopwatch class internally to record the time passed since .Start() was called and adds this interval to the start time that was provided in its constructor. This way, you can make your code run at any point in time and enable you to test the behavior of your code where it depends on the date and/or time.
In some applications, the current date and time are used to generate timestamps for data or logs. In such cases, the resolution of the clock used can be important. You may not, for example, want to generate two identical timestamps for different records if you use the timestamps to see in which order these records were created or modified. The default clock is unsuited for this purpose, because its resolution - the number of times its value is updated between consecutive calls to .LocalDateAndTime() or .UtcDateAndTime() - is not so high, and so you may end up with the same value if two invocations are carried out quickly after one another.
If you really require a high time resolution, you can use the HighResolutionClock class. The main property of this class is that each instance guarantees a fresh (higher) value each time a call to one of its time-reading methods is made - with one single tick (a 100 nanosecond step) as a minimal difference - even if called from different threads simultaniously. As such, by overriding the default clock with an instance of the HighResolutionClock, each and every timestamp will be different and in strictly ascending order:
using (var clock = HighResolutionClock.StartNew())
using (Clock.Override(clock))
{
// This is guaranteed: timestamp_y > timestamp_x
var timestamp_x = Clock.Current.UtcDateAndTime();
var timestamp_y = Clock.Current.UtcDateAndTime();
}As shown in the code above, you can create a new instance of the HighResolutionClock by calling one of its static .StartNew() methods. The default one returns a high-resolution alternative to the basic Clock.Default instance. This means that the default instance will return timestamps indirectly based on the values returned by DateTimeOffset.Now and DateTimeOffset.UtcNow properties.
In fact, the default instance of the HighResolutionClock class bases its values on the values returned by Clock.Default - it just adds a high resolution behavior on top of it to compensate for the low-resolution behavior of the default clock. This means you can also create an instance of the HighResolutionClock class based on a different IClock-instance, like a StopwatchClock, to combine absolute control over dates and times with the high resolution properties provided by the HighResolutionClock class:
var stopwatchClock = new StopwatchClock(new DateTimeOffset(1995, 12, 31, 23, 59, 59, TimeSpan.Zero));
stopwatchClock.Start();
using (var highResolutionClock = HighResolutionClock.StartNew(stopwatchClock))
using (Clock.OverrideAsyncLocal(highResolutionClock))
{
// This is guaranteed: timestamp_y > timestamp_x
// Timestamps now in range of December '95.
var timestamp_x = Clock.Current.UtcDateAndTime();
var timestamp_y = Clock.Current.UtcDateAndTime();
}
stopwatchClock.Stop(); Note that the HighResolutionClock class implements IDisposable, so make sure you dispose of it when you're done using it.
Besides specifying your own IClock instance to base the values of a HighResolutionClock on, you may also specify a custom synchronizationInterval. Internally, the HighResolutionClock class uses a Stopwatch to increase its timing resolution. Each time you request a new timestamp from an instance, the HighResolutionClock class takes a sample from the referenceClock you provided (or Clock.Default) and adds the interval of the Stopwatch to this value (and some other trickery to ensure strict increasing values are returned.) This approach does have the downside of running the risk that the times returned by the HighResolutionClock will slowly deviate from the actual values returned by the referenceClock. For this reason, the HighResolutionClock must synchronize its values with its referenceClock from time to time to ensure this deviation is kept within certain boundaries. By default, the HighResolutionClock does this every 10 seconds (HighResolutionClock.DefaultSynchronizationInterval), which has proven to be a well balanced period to synchronize with the default clock. When you provide your own IClock as a referenceClock, however, you may want to specify your own synchronizationInterval as well to optimize the behavior of the HighResolutionClock for the referenceClock you provided:
using (var highResolutionClock = HighResolutionClock.StartNew(customClock, TimeSpan.FromSeconds(0.5))
using (Clock.OverrideAsyncLocal(highResolutionClock))
{
// This is guaranteed: timestamp_y > timestamp_x
// Also, the HighResolutionClock now synchronizes more often.
var timestamp_x = Clock.Current.UtcDateAndTime();
var timestamp_y = Clock.Current.UtcDateAndTime();
} A low interval will, of course, mean less deviation from the referenceClock and thus better precision, with the downside of a small performance hit because more synchronizations are carried out over time. You can also completely disable synchronization by specifying an interval of TimeSpan.Zero.
Even tough the built-in clocks will probably cover most common scenarios, there will be times where you will want to implement you own clock. You can do this simply by implementing the IClock-interface and implement its members. When doing so, you must keep in mind the following:
- The implementation must be thread-safe.
- The absolute values returned by each member are not important, as long as a succeeding invocation on a single thread never returns a value that is lower than a value already returned on that thread. (In other words, time can never go backwards.)
Having said that, the easiest way to create a custom IClock-implementation is by creating a sub-class of the Clock class. This leaves you only to implement the abstract Clock.UtcDateAndTime() method:
public sealed class MyClock : Clock
{
public override DateTimeOffset UtcDateAndTime()
{
// Implementation goes here...
}
}