Search code examples
pythonpython-3.xscheduled-taskssched

Print sched queue with human readable time


I want to print the queue from sched scheduler with human-readable time. But whatever I try I get weird results despite the event are executed in proper time and order.

How can achieve that?

Current code

scheduler = sched.scheduler(timefunc=time.time)

# Add some events into a scheduler

def executing_at_message(event):
    date = datetime.fromtimestamp(event.time)
    print(f"{date.hour}:{date.minute}: {event.action.__doc__}")

for event in scheduler.queue:
    executing_at_message(event)

Solution

  • I haven't changed anything, apart from adding the actual jobs, and this seems to work fine.

    import sched
    from datetime import datetime
    import time
    
    scheduler = sched.scheduler(timefunc=time.time)
    
    def main():
        """Do the main thing"""
        time.sleep(3)
        print('Done main')
    
    def other():
        """Do the other thing"""
        time.sleep(2)
        print('Done other')
    
    scheduler.enter(3, 2, main)
    scheduler.enter(2, 1, other)
    
    def executing_at_message(event):
        date = datetime.fromtimestamp(event.time)
        print(f"{date.hour}:{date.minute}:{date.second} {event.action.__doc__}")
    
    for event in scheduler.queue:
        executing_at_message(event)
    
    

    output:

    22:41:45 Do the other thing
    22:41:46 Do the main thing