SystemClockChangeWatcher
February 11th, 2010 Posted in AS3, Adobe AIR, Flash, Flex, GeneralWhen dealing with time sensitive applications (pretty much anything that needs to compare local times and/or remote server time) changes in the system clock can at best make for a bad user experience and at worst provide a means of circumventing critical business logic.
Consider the situation where a user or system event is scheduled for a particular date/time. The most common implementation would be to calculate the time in milliseconds between now and the scheduled event and start a timeout with a delay equal to that time.
The problem with this approach is that in the conversion from the specific date to a length in milliseconds we lose information about the actual date requested. This means that changes to system clock (event legitimate ones such as daylight savings) will mean the previously calculated time is now invalid. For example: Its 2PM and we schedule an event for 4:30PM, we calculate the time between now and then to be 2.5 hours (9000000ms), at some point the system clock changes back 30 minutes. This means that the scheduled event will now occur (according to the new time) 30 minutes too late (note: this example assumes that its important to make things happen at the apparent local time).
A different implementation would be to have a timer which, upon each tick, evaluates whether the scheduled time has arrived. This works fine for a single event, but becomes very wasteful with many events and perhaps your application needs to know about changes to the system clock even when you don’t have a time based event scheduled.
Step up the SystemClockChangeWatcher. I’m not touting this a fix-all for the use cases discussed above, the logic the class encapsulates would be better implemented as a part of a wider scheduling system. Encapsulated as below you lose the ability to manage the Timer instance with your other scheduling Timers. However, as a functioning example of how to solve the problem it works well and would fit nicely into applications with few other Timers.
Here it is:
