This project provides a simple, scalable mechanism for scheduling arbitrary events with a high degree of precision. Key features of this approach include: high-precision timing to the extent provided by the architecture, good scalability that does not require the use of one thread per pending event, flexible choice of actions that can be scheduled. This project assumes the use of a single process, cross-process scheduling is outside this scope.
In certain high-precision environments, such as high-frequency trading, it is important to schedule tasks with a great degree of precision. For instance, you may want to cancel an order exactly 1.5 seconds after it has been submitted. One solution is to spin off separate threads for each task and using
Thread.Sleep() to cause the thread to wake up at the given time. While threads are cheap, this approach requires one thread per pending task and may not scale well.
Alternatively, the technique used here relies on a tight loop that wakes up every 20 milliseconds and checks for any pending events that have been scheduled for the current period. An arbitrary number of events can be scheduled for any 20 millisecond period.
Using the Code
TaskScheduler has the main event loop, which is invoked when the singleton instance is constructed. To schedule an event, simply provide the
ScheduledEventDelegate (i.e. method to execute), together with a
TimeSpan indicating how long to delay the start of the event as well as the list of input parameters. E.g.
(TaskScheduler.Instance.Action1, TimeSpan.FromMilliseconds(5000), "anObject");
To shut down the event loop, simply set the
Program.m_KeepRunning property to
- 24th March, 2009: Initial version