mfjones
mfjones

Reputation: 13

Getting the remaining time for the next job to be executed in schedule package?

I am trying to print the remaining time for the next job. Here is some sample code:

import schedule
import time

def Job():
    #doing something...

schedule.every(1).minutes.do(Job)

while True:
    schedule.run_pending()
    time.sleep(1)
    print(schedule.Scheduler.next_run) # prints "<property object at 0x044FE7E0>"
    time.sleep(5)

How do I do it correctly?

Upvotes: 1

Views: 1890

Answers (1)

Gino Mempin
Gino Mempin

Reputation: 29600

This answer refers to the schedule package.

According to the API documentation, the correct API to call is the schedule.next_run() method:

schedule.next_run()

Calls next_run on the default scheduler instance.

According to the docs, next_run is a property (<property object at 0x044FE7E0>) that supposedly stores the datetime object when the next job will be run. But you'll have to access it from the Scheduler instance object that's running your job. What you did was access it from the Scheduler class itself.

Rather than track down the Scheduler instance, just use the available API:

schedule.every(1).minutes.do(Job)

while True:
    schedule.run_pending()
    time.sleep(1)
    time_of_next_run = schedule.next_run()
    print(type(time_of_next_run))  # <class 'datetime.datetime'>
    print(time_of_next_run)        # 2019-09-22 13:48:06.566073

Now to get the remaining time, you just need to get the difference between the date/time now and date/time when the next job will be run. Python's datetime module supports simple subtraction and returns a timedelta object:

while True:
    schedule.run_pending()
    time.sleep(1)
    time_of_next_run = schedule.next_run()
    time_now = datetime.now()
    time_remaining = time_of_next_run - time_now
    print(time_remaining)

That will print something like:

0:00:58.994702
0:00:57.994054
0:00:56.989839
0:00:55.987161
0:00:54.982645
0:00:53.980167
...

Take a look at the datetime and timedelta for more formatting options.

print(f"{time_remaining.seconds} seconds left..")  # 58 seconds left..

Upvotes: 3

Related Questions