pythonsched

How to correctly use enterabs from scheduler


I'm trying to schedule something to run periodically, using the code below:

import sched
import time
from datetime import datetime, timedelta

def foo(s, t_end):
    now = datetime.now()
    print(now)
    # Schedule the next run of this function, but only if it'll be before 't_end'
    next_run = now + timedelta(seconds=1)
    if next_run <= t_end:
        s.enter(1, 1, foo, (s, t_end,))
        # s.enterabs(next_run, 1, foo, (s, t_end,)) # <-- why doesn't this work?

if __name__ == '__main__':
    s = sched.scheduler(time.time, time.sleep)
    t_end = datetime.now() + timedelta(seconds=5)
    foo(s, t_end)
    s.run()

This runs exactly like it should... the script calls foo exactly 5 times and then exits (with 1 second delay between the calls).

But if I change the s.enter(...) to s.enterabs(...) and pass in the calculated time when foo should be called again, it throws the following error:

Traceback (most recent call last):
  File "/tmp/test.py", line 18, in <module>
    s.run()
  File "/usr/lib/python3.9/sched.py", line 141, in run
    if time > now:
TypeError: '>' not supported between instances of 'datetime.datetime' and 'float'

What am I doing wrong?


Solution

  • OK I figured this out. In the call to s.enterabs(...), I need to pass next_run.timestamp() as the first argument (not just next_run).