Renamed DefaultTimeSource to GenericTimeSource; the generic time source will now detect when the system date/time is adjusted; made some progress on the Scheduler implementation; wrote some unit tests for the Scheduler class

git-svn-id: file:///srv/devel/repo-conversion/nusu@144 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2009-06-08 20:32:14 +00:00
parent 2426868cce
commit 4b9002b520
8 changed files with 519 additions and 29 deletions

View File

@ -122,12 +122,15 @@
<Compile Include="Source\Plugins\PrototypeFactory.Test.cs">
<DependentUpon>PrototypeFactory.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\DefaultTimeSource.Test.cs">
<DependentUpon>DefaultTimeSource.cs</DependentUpon>
<Compile Include="Source\Scheduling\GenericTimeSource.Test.cs">
<DependentUpon>GenericTimeSource.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\ITimeSource.cs" />
<Compile Include="Source\Scheduling\Scheduler.cs" />
<Compile Include="Source\Scheduling\DefaultTimeSource.cs" />
<Compile Include="Source\Scheduling\GenericTimeSource.cs" />
<Compile Include="Source\Scheduling\Scheduler.Test.cs">
<DependentUpon>Scheduler.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\WindowsTimeSource.cs" />
<Compile Include="Source\Scheduling\WindowsTimeSource.Test.cs">
<DependentUpon>WindowsTimeSource.cs</DependentUpon>

View File

@ -104,12 +104,15 @@
<Compile Include="Source\Plugins\PrototypeFactory.Test.cs">
<DependentUpon>PrototypeFactory.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\DefaultTimeSource.Test.cs">
<DependentUpon>DefaultTimeSource.cs</DependentUpon>
<Compile Include="Source\Scheduling\GenericTimeSource.Test.cs">
<DependentUpon>GenericTimeSource.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\ITimeSource.cs" />
<Compile Include="Source\Scheduling\Scheduler.cs" />
<Compile Include="Source\Scheduling\DefaultTimeSource.cs" />
<Compile Include="Source\Scheduling\GenericTimeSource.cs" />
<Compile Include="Source\Scheduling\Scheduler.Test.cs">
<DependentUpon>Scheduler.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\WindowsTimeSource.cs" />
<Compile Include="Source\Scheduling\WindowsTimeSource.Test.cs">
<DependentUpon>WindowsTimeSource.cs</DependentUpon>

View File

@ -28,16 +28,16 @@ using NUnit.Framework;
namespace Nuclex.Support.Scheduling {
/// <summary>Unit Test for the default scheduler time source</summary>
/// <summary>Unit Test for the generic scheduler time source</summary>
[TestFixture]
public class DefaultTimeSourceTest {
public class GenericTimeSourceTest {
/// <summary>
/// Verifies that the time source's default constructor is working
/// </summary>
[Test]
public void TestDefaultConstructor() {
DefaultTimeSource timeSource = new DefaultTimeSource();
GenericTimeSource timeSource = new GenericTimeSource();
}
/// <summary>
@ -45,7 +45,7 @@ namespace Nuclex.Support.Scheduling {
/// </summary>
[Test]
public void TestCurrentUtcTime() {
DefaultTimeSource timeSource = new DefaultTimeSource();
GenericTimeSource timeSource = new GenericTimeSource();
Assert.That(
timeSource.CurrentUtcTime, Is.EqualTo(DateTime.UtcNow).Within(10).Seconds
@ -58,7 +58,7 @@ namespace Nuclex.Support.Scheduling {
/// </summary>
[Test]
public void TestTicksWithStopwatch() {
DefaultTimeSource timeSource = new DefaultTimeSource(true);
GenericTimeSource timeSource = new GenericTimeSource(true);
long ticks1 = timeSource.Ticks;
long ticks2 = timeSource.Ticks;
@ -71,7 +71,7 @@ namespace Nuclex.Support.Scheduling {
/// </summary>
[Test]
public void TestTicksWithTickCount() {
DefaultTimeSource timeSource = new DefaultTimeSource(false);
GenericTimeSource timeSource = new GenericTimeSource(false);
long ticks1 = timeSource.Ticks;
long ticks2 = timeSource.Ticks;
@ -83,7 +83,7 @@ namespace Nuclex.Support.Scheduling {
/// </summary>
[Test]
public void TestWaitOne() {
DefaultTimeSource timeSource = new DefaultTimeSource();
GenericTimeSource timeSource = new GenericTimeSource();
AutoResetEvent waitEvent = new AutoResetEvent(true);
Assert.IsTrue(timeSource.WaitOne(waitEvent, TimeSpan.FromMilliseconds(1).Ticks));

View File

@ -26,13 +26,20 @@ using System.Threading;
namespace Nuclex.Support.Scheduling {
/// <summary>
/// Default time source implementation using the Stopwatch or Environment.TickCount
/// Generic time source implementation using the Stopwatch or Environment.TickCount
/// </summary>
public class DefaultTimeSource : ITimeSource {
public class GenericTimeSource : ITimeSource {
/// <summary>Number of ticks (100 ns intervals) in a millisecond</summary>
private const long TicksPerMillisecond = 10000;
/// <summary>Tolerance for the detection of a date/time adjustment</summary>
/// <remarks>
/// If the current system date/time jumps by more than this tolerance into any
/// direction, the default time source will trigger the DateTimeAdjusted event.
/// </remarks>
private const long TimeAdjustmentToleranceTicks = 75 * TicksPerMillisecond;
/// <summary>Called when the system date/time are adjusted</summary>
/// <remarks>
/// An adjustment is a change out of the ordinary, eg. when a time synchronization
@ -42,13 +49,13 @@ namespace Nuclex.Support.Scheduling {
public event EventHandler DateTimeAdjusted;
/// <summary>Initializes the static fields of the default time source</summary>
static DefaultTimeSource() {
static GenericTimeSource() {
tickFrequency = 10000000.0;
tickFrequency /= (double)Stopwatch.Frequency;
}
/// <summary>Initializes the default time source</summary>
public DefaultTimeSource() : this(Stopwatch.IsHighResolution) { }
public GenericTimeSource() : this(Stopwatch.IsHighResolution) { }
/// <summary>Initializes the default time source</summary>
/// <param name="useStopwatch">
@ -67,23 +74,25 @@ namespace Nuclex.Support.Scheduling {
/// but then your won't profit from the high-resolution timer if one is available.
/// </para>
/// </remarks>
public DefaultTimeSource(bool useStopwatch) {
public GenericTimeSource(bool useStopwatch) {
this.useStopwatch = useStopwatch;
checkForTimeAdjustment();
}
/// <summary>Waits for an AutoResetEvent become signalled</summary>
/// <summary>Waits for an AutoResetEvent to become signalled</summary>
/// <param name="waitHandle">WaitHandle the method will wait for</param>
/// <param name="ticks">Number of ticks to wait</param>
/// <returns>
/// True if the WaitHandle was signalled, false if the timeout was reached
/// </returns>
public virtual bool WaitOne(AutoResetEvent waitHandle, long ticks) {
checkForTimeAdjustment();
// Force a timeout at least each second so the caller can check the system time
// since we're not able to provide the DateTimeAdjusted notification
int milliseconds = (int)(ticks / TicksPerMillisecond);
return waitHandle.WaitOne(Math.Min(1000, milliseconds), false);
}
/// <summary>Current system time in UTC format</summary>
@ -127,6 +136,41 @@ namespace Nuclex.Support.Scheduling {
}
}
/// <summary>
/// Checks whether the system/date time have been adjusted since the last call
/// </summary>
private void checkForTimeAdjustment() {
// Grab the current date/time and timer ticks in one go
DateTime currentLocalTime = DateTime.Now;
long currentTicks = Ticks;
// Calculate the number of timer ticks that have passed since the last check and
// extrapolate the local date/time we should be expecting to see
long ticksSinceLastCheck = currentTicks - lastCheckedTicks;
DateTime expectedLocalTime = new DateTime(
lastCheckedLocalTime.Ticks + ticksSinceLastCheck, DateTimeKind.Local
);
// Find out by what amount the actual local date/time deviates from
// the extrapolated date/time and trigger the date/time adjustment event if
// we can reasonably assume that the system date/time have been adjusted.
long deviationTicks = Math.Abs(expectedLocalTime.Ticks - currentLocalTime.Ticks);
if(deviationTicks > TimeAdjustmentToleranceTicks) {
OnDateTimeAdjusted(this, EventArgs.Empty);
}
// Remember the current local date/time and timer ticks for the next run
this.lastCheckedLocalTime = currentLocalTime;
this.lastCheckedTicks = currentTicks;
}
/// <summary>Last local time we checked for a date/time adjustment</summary>
private DateTime lastCheckedLocalTime;
/// <summary>Timer ticks at which we last checked the local time</summary>
private long lastCheckedTicks;
/// <summary>Number of ticks per Stopwatch time unit</summary>
private static double tickFrequency;
/// <summary>Whether ot use the Stopwatch class for measuring time</summary>

View File

@ -25,7 +25,7 @@ using System.Threading;
namespace Nuclex.Support.Scheduling {
/// <summary>Provides time measurement and change notification services</summary>
interface ITimeSource {
public interface ITimeSource {
/// <summary>Called when the system date/time are adjusted</summary>
/// <remarks>
@ -35,7 +35,7 @@ namespace Nuclex.Support.Scheduling {
/// </remarks>
event EventHandler DateTimeAdjusted;
/// <summary>Waits for an AutoResetEvent become signalled</summary>
/// <summary>Waits for an AutoResetEvent to become signalled</summary>
/// <param name="waitHandle">WaitHandle the method will wait for</param>
/// <param name="ticks">Number of ticks to wait</param>
/// <returns>

View File

@ -0,0 +1,105 @@
#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2009 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
#if UNITTEST
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;
using NUnit.Framework;
#if false
namespace Nuclex.Support.Scheduling {
/// <summary>Unit Test for the scheduler</summary>
[TestFixture]
public class SchedulerTest {
/// <summary>
/// Test whether the Scheduler can explicitely create a windows time source
/// </summary>
[Test]
public void TestCreateWindowsTimeSource() {
ITimeSource timeSource = Scheduler.CreateTimeSource(true);
try {
Assert.That(timeSource is WindowsTimeSource);
}
finally {
IDisposable disposableTimeSource = timeSource as IDisposable;
if(disposableTimeSource != null) {
disposableTimeSource.Dispose();
}
}
}
/// <summary>
/// Test whether the Scheduler can explicitely create a generic time source
/// </summary>
[Test]
public void TestCreateGenericTimeSource() {
ITimeSource timeSource = Scheduler.CreateTimeSource(false);
try {
Assert.That(timeSource is GenericTimeSource);
}
finally {
IDisposable disposableTimeSource = timeSource as IDisposable;
if(disposableTimeSource != null) {
disposableTimeSource.Dispose();
}
}
}
/// <summary>
/// Test whether the Scheduler can automatically choose the right time source
/// </summary>
[Test]
public void TestCreateDefaultTimeSource() {
ITimeSource timeSource = Scheduler.CreateDefaultTimeSource();
try {
Assert.IsNotNull(timeSource);
}
finally {
IDisposable disposableTimeSource = timeSource as IDisposable;
if(disposableTimeSource != null) {
disposableTimeSource.Dispose();
}
}
}
/// <summary>
/// Verifies that the default constructor of the scheduler is working
/// </summary>
[Test]
public void TestDefaultConstructor() {
using(Scheduler scheduler = new Scheduler()) { }
}
}
} // namespace Nuclex.Support.Scheduling
#endif
#endif // UNITTEST

View File

@ -23,20 +23,355 @@ using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace Nuclex.Support.Scheduling {
using Nuclex.Support.Collections;
#if false
namespace Nuclex.Support.Scheduling {
/// <summary>Schedules actions for execution at a future point in time</summary>
public class Scheduler : IDisposable {
/// <summary>Immediately releases all resources owned by the instance</summary>
public void Dispose() {
/// <summary>One tick is 100 ns, meaning 10000 ticks equal 1 ms</summary>
private const long TicksPerMillisecond = 10000;
#region class TimeSourceSingleton
/// <summary>
/// Manages the singleton instance of the scheduler's default time source
/// </summary>
private class TimeSourceSingleton {
/// <summary>
/// Explicit static constructor to guarantee the singleton is initialized only
/// when a static member of this class is accessed.
/// </summary>
static TimeSourceSingleton() { } // Do not remove!
/// <summary>The singleton instance of the default time source</summary>
internal static readonly ITimeSource Instance = Scheduler.CreateDefaultTimeSource();
}
#endregion // class TimeSourceSingleton
#region class Notification
/// <summary>Scheduled notification</summary>
private class Notification {
/// <summary>Initializes a new notification</summary>
/// <param name="intervalTicks">
/// Interval in which the notification will re-executed
/// </param>
/// <param name="nextDueTicks">
/// Time source ticks the notification is next due at
/// </param>
/// <param name="absoluteUtcTime">
/// Absolute time in UTC at which the notification is due
/// </param>
/// <param name="callback">
/// Callback to be invoked when the notification is due
/// </param>
public Notification(
long intervalTicks,
long nextDueTicks,
DateTime absoluteUtcTime,
Delegate callback
) {
this.IntervalTicks = intervalTicks;
this.NextDueTicks = nextDueTicks;
this.AbsoluteUtcTime = absoluteUtcTime;
this.Callback = callback;
this.Cancelled = false;
}
/// <summary>
/// Ticks specifying the interval in which the notification will be re-executed
/// </summary>
public long IntervalTicks;
/// <summary>Next due time for this notification</summary>
public long NextDueTicks;
/// <summary>Absolute time in UTC at which the notification is due</summary>
/// <remarks>
/// Only stored for notifications scheduled in absolute time, meaning they
/// have to be adjusted if the system date/time changes
/// </remarks>
public DateTime AbsoluteUtcTime;
/// <summary>Callback that will be invoked when the notification is due</summary>
public Delegate Callback;
/// <summary>Whether the notification has been cancelled</summary>
public bool Cancelled;
}
#endregion // class Notification
/// <summary>Initializes a new scheduler using the default time source</summary>
public Scheduler() : this(DefaultTimeSource) { }
/// <summary>Initializes a new scheduler using the specified time source</summary>
/// <param name="timeSource">Source source the scheduler will use</param>
public Scheduler(ITimeSource timeSource) {
this.timeSource = timeSource;
this.notifications = new PriorityQueue<Notification>();
this.notificationWaitEvent = new AutoResetEvent(false);
this.timerThread = new Thread(new ThreadStart(runTimerThread));
this.timerThread.Name = "Nuclex.Support.Scheduling.Scheduler";
this.timerThread.Priority = ThreadPriority.Highest;
this.timerThread.IsBackground = true;
this.timerThread.Start();
}
/// <summary>Immediately releases all resources owned by the instance</summary>
public void Dispose() {
if(this.timerThread != null) {
this.endRequested = true;
this.notificationWaitEvent.Set();
// Wait for the timer thread to exit. If it doesn't exit in 10 seconds (which is
// a lot of time given that it doesn't do any real work), forcefully abort
// the thread. This may risk some leaks, but it's the only thing we can do.
Trace.Assert(
this.timerThread.Join(2500), "Scheduler timer thread did not exit in time"
);
// Get rid of the notification wait event now that we've made sure that
// the timer thread is down.
this.notificationWaitEvent.Close();
// Help the GC a bit
this.notificationWaitEvent = null;
this.notifications = null;
this.timeSource = null;
// Set to null so we don't attempt to end the thread again if Dispose() is
// called multiple times.
this.timerThread = null;
}
}
/// <summary>Schedules a notification at the specified absolute time</summary>
/// <param name="notificationTime">
/// Absolute time at which the notification will occur
/// </param>
/// <param name="callback">
/// Callback that will be invoked when the notification is due
/// </param>
/// <returns>A handle that can be used to cancel the notification</returns>
/// <remarks>
/// The notification is scheduled for the indicated absolute time. If the system
/// enters/leaves daylight saving time or the date/time is changed (for example
/// when the system synchronizes with an NTP server), this will affect
/// the notification. So if you need to be notified after a fixed time, use
/// the NotifyIn() method instead.
/// </remarks>
public object NotifyAt(DateTime notificationTime, Delegate callback) {
if(notificationTime.Kind == DateTimeKind.Unspecified) {
throw new ArgumentException(
"Notification time is neither UTC or local", "notificationTime"
);
}
DateTime notificationTimeUtc = notificationTime.ToUniversalTime();
long remainingTicks = notificationTimeUtc.Ticks - DateTime.UtcNow.Ticks;
long nextDueTicks = this.timeSource.Ticks + remainingTicks;
return scheduleNotification(
new Notification(
0,
nextDueTicks,
notificationTimeUtc,
callback
)
);
}
/// <summary>Schedules a notification after the specified time span</summary>
/// <param name="delay">Delay after which the notification will occur</param>
/// <param name="callback">
/// Callback that will be invoked when the notification is due
/// </param>
/// <returns>A handle that can be used to cancel the notification</returns>
public object NotifyIn(TimeSpan delay, Delegate callback) {
return scheduleNotification(
new Notification(
0,
delay.Ticks,
DateTime.MinValue,
callback
)
);
}
/// <summary>
/// Schedules a notification after the specified amount of milliseconds
/// </summary>
/// <param name="delayMilliseconds">
/// Number of milliseconds after which the notification will occur
/// </param>
/// <param name="callback">
/// Callback that will be invoked when the notification is due
/// </param>
/// <returns>A handle that can be used to cancel the notification</returns>
public object NotifyIn(int delayMilliseconds, Delegate callback) {
return scheduleNotification(
new Notification(
0,
(long)delayMilliseconds * TicksPerMillisecond,
DateTime.MinValue,
callback
)
);
}
/// <summary>
/// Schedules a recurring notification after the specified time span
/// </summary>
/// <param name="delay">Delay after which the first notification will occur</param>
/// <param name="interval">Interval at which the notification will be repeated</param>
/// <param name="callback">
/// Callback that will be invoked when the notification is due
/// </param>
/// <returns>A handle that can be used to cancel the notification</returns>
public object NotifyEach(TimeSpan delay, TimeSpan interval, Delegate callback) {
return scheduleNotification(
new Notification(
interval.Ticks,
delay.Ticks,
DateTime.MinValue,
callback
)
);
}
/// <summary>
/// Schedules a recurring notification after the specified amount of milliseconds
/// </summary>
/// <param name="delayMilliseconds">
/// Milliseconds after which the first notification will occur
/// </param>
/// <param name="intervalMilliseconds">
/// Interval in milliseconds at which the notification will be repeated
/// </param>
/// <param name="callback">
/// Callback that will be invoked when the notification is due
/// </param>
/// <returns>A handle that can be used to cancel the notification</returns>
public object NotifyEach(
int delayMilliseconds, int intervalMilliseconds, Delegate callback
) {
return scheduleNotification(
new Notification(
(long)intervalMilliseconds * TicksPerMillisecond,
(long)delayMilliseconds * TicksPerMillisecond,
DateTime.MinValue,
callback
)
);
}
/// <summary>Returns the default time source for the scheduler</summary>
public static ITimeSource DefaultTimeSource {
get { return TimeSourceSingleton.Instance; }
}
/// <summary>Creates a new default time source for the scheduler</summary>
/// <param name="useWindowsTimeSource">
/// Whether the specialized windows time source should be used
/// </param>
/// <returns>The newly created time source</returns>
internal static ITimeSource CreateTimeSource(bool useWindowsTimeSource) {
if(useWindowsTimeSource) {
return new WindowsTimeSource();
} else {
return new GenericTimeSource();
}
}
/// <summary>Creates a new default time source for the scheduler</summary>
/// <returns>The newly created time source</returns>
internal static ITimeSource CreateDefaultTimeSource() {
return CreateTimeSource(WindowsTimeSource.Available);
}
/// <summary>Schedules a notification for processing by the timer thread</summary>
/// <param name="notification">Notification that will be scheduled</param>
/// <returns>The scheduled notification</returns>
private object scheduleNotification(Notification notification) {
lock(this.notifications) {
this.notifications.Enqueue(notification);
// If this notification has become that next due notification, wake up
// the timer thread so it can adjust its sleep period.
if(ReferenceEquals(this.notifications.Peek(), notification)) {
this.notificationWaitEvent.Set();
}
}
return notification;
}
/// <summary>Executes the timer thread</summary>
private void runTimerThread() {
for(; ; ) {
// Get the notification that is due next and wait for it. When no notifications
// are queued, wait indefinitely until we're signalled
Notification nextDueNotification = getNextDueNotification();
if(nextDueNotification == null) {
this.notificationWaitEvent.WaitOne();
} else {
long remainingTicks = nextDueNotification.NextDueTicks - this.timeSource.Ticks;
this.timeSource.WaitOne(this.notificationWaitEvent, remainingTicks);
}
// Have we been woken up because the Scheduler is being disposed?
if(this.endRequested) {
break;
}
//if(nextDueNotification.AbsoluteUtcTime !=
}
}
/// <summary>Retrieves the notification that is due next</summary>
/// <returns>The notification that is due next</returns>
private Notification getNextDueNotification() {
lock(this.notifications) {
if(this.notifications.Count == 0) {
return null;
} else {
Notification nextDueNotification = this.notifications.Peek();
while(nextDueNotification.Cancelled) {
this.notifications.Dequeue();
nextDueNotification = this.notifications.Peek();
}
return nextDueNotification;
}
}
}
/// <summary>Time source used by the scheduler</summary>
private ITimeSource timeSource;
/// <summary>Thread that will wait for the next scheduled event</summary>
private Thread timerThread;
/// <summary>Notifications in the scheduler's queue</summary>
private PriorityQueue<Notification> notifications;
/// <summary>Event used by the timer thread to wait for the next notification</summary>
private AutoResetEvent notificationWaitEvent;
/// <summary>Whether the timer thread should end</summary>
private volatile bool endRequested;
}
#endif
} // namespace Nuclex.Support.Scheduling
#endif

View File

@ -31,7 +31,7 @@ namespace Nuclex.Support.Scheduling {
/// <summary>
/// Time source that makes use of additional features only available on Windows
/// </summary>
public class WindowsTimeSource : DefaultTimeSource, IDisposable {
public class WindowsTimeSource : GenericTimeSource, IDisposable {
/// <summary>Number of ticks (100 ns intervals) in a millisecond</summary>
private const long TicksPerMillisecond = 10000;
@ -50,7 +50,7 @@ namespace Nuclex.Support.Scheduling {
}
}
/// <summary>Waits for an AutoResetEvent become signalled</summary>
/// <summary>Waits for an AutoResetEvent to become signalled</summary>
/// <param name="waitHandle">WaitHandle the method will wait for</param>
/// <param name="ticks">Number of ticks to wait</param>
/// <returns>