Saturday, 27 October 2012

Design a timer class

Design a timer class. The users of your class should be able to register to your class with the time in secs and their callbacks. These callbacks are called as the time expires.

  • The timer runs in its own thread, and it sleeps for 1 sec (since, the interviewer had asked for 1 second as the granularity)
  • It maintains a list of  'Task/Runnable' along with the remaining time to expire.
  • Every time the timer wakes up after a sec, it reduces the expiry time for each task by 1 sec.
  • And for all those tasks for which the expiry reaches zero, their callbacks are called.
  • I suggested a faster way (where one doesn't need to iterate the list of tasks) if the timer was limited to a fixed number of seconds using an circular array of seconds.

No comments:

Post a Comment