2

I have a scheduling function and a scheduler with a queue of future events ordered by time. I'm using UNIX timestamps and the regular time.time(). One fragment of the scheduler is roughly equivalent to this:

# select the nearest event (eventfunc at eventime)
sleeptime = eventtime - time.time()
# if the sleep gets interrupted,
# the whole block will be restarted
interruptible_sleep(sleeptime)
eventfunc()

where the eventtime could be computed either based on a delay:

eventtime = time.time() + delay_seconds

or based on an exact date and time, e.g.:

eventtime = datetime(year,month,day,hour,min).timestamp()

Now we have the monotonic time in Python. I'm considering to modify the scheduler to use the monotonic time. Schedulers are supposed to use the monotonic time they say.

No problem with delays:

sleeptime = eventtime - time.monotonic()

where:

eventtime = time.monotonic() + delay_seconds

But with the exact time I think the best way is to leave the code as it is. Is that correct?

If yes, I would need two event queues, one based on monotonic time and one based on regular time. I don't like that idea much.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • You may wish to look at the [`sched` standard module](https://docs.python.org/3/library/sched.html). It's designed to be independent from time manipulation backend and uses `time.monotonic` by default. – ivan_pozdeev Oct 24 '17 at 07:58

1 Answers1

1

As I said in the comment, your code duplicates the functionality of the sched standard module - so you can as well use solving this problem as a convenient excuse to migrate to it.

That said,

  • what you're supposed to do if system time jumps forward or backward is task-specific.
  • time.monotonic() is designed for cases when you need to do things with set intervals between them regardless of anything
  • So, if your solution is expected to instead react to time jumps by running scheduled tasks sooner or later than it otherwise would, in accordance with the new system time, you have no reason to use monotonic time.

If you wish to do both, then you either need two schedulers, or tasks with timestamps of the two kinds.

In the latter case, the scheduler will need to convert one type to the other (every time it calculates how much to wait/whether to run the next task) - for which time provides no means.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • My program only assumes that NTP is well configured, i.e. the server has the exact time without jumps. However it's always good to have a more robust solution just for the case. That's why I'm investigating the pros and cons of the monotonic clock. You did not directly answer my question. Are two event queues required to take advantage of the monotonic clock in a scheduler? One queue - for delays, intervals, etc. - working with `time.monotonic` and another queue - for scheduling at exact date/times - working with `time.time`? – VPfB Oct 24 '17 at 09:24