Python schedule "Time is freezing"

Viewed 75

I am using schedule to do functions that work with the real-time datetime.datetime.now(). But when calling the function datetime.datetime.now() i always get start time schedule script.

Example:

import schedule
import time
import datetime


schedule.every(2).minutes.do(print, datetime.datetime.now().strftime("%d-%m-%Y %H:%M"))


while 1:
    schedule.run_pending()
    time.sleep(1)

Example result:

28-04-2021 19:59
28-04-2021 19:59
28-04-2021 19:59
28-04-2021 19:59

Does anyone have any ideas how one can get real time during the execution of the scheduler?

Python => 3.8
schedule => 1.1.0
2 Answers

This is because the return value of now() gets saved in memory. Pass a lambda or function to ensure it is dynamically calculated:

import schedule
import time
import datetime

schedule.every(2).minutes.do(
    lambda: print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M"))
)

while 1:
    schedule.run_pending()
    time.sleep(1)

This is because value of now is already loaded into memory.

Try this

    import schedule
import time
import datetime

schedule.every(2).minutes.do(print, datetime.datetime.now().strftime("%d-%m-%Y %H:%M"))


while 1:
    schedule.run_pending()
    time.sleep(1)
Related