I need a code to schedule my Python calculations which does some operation every two hours. So I have written this code to test how it is working and scheduled it to run every minute for testing.
import schedule
from datetime import datetime
def do_job():
print("Inside do_job at ", datetime.now().strftime("%H:%M:%S"))
schedule.every(1).minutes.do(do_job)
print("Starting at ",datetime.now().strftime("%H:%M:%S"))
while True:
schedule.run_pending()
This code is working as expected. The do_job() def is getting called every minute. The only thing is the do_job method is not getting called as soon as I run the script. It's executed from the next minute. This is the output when I run the above script.
Starting at 15:15:52
Inside do_job at 15:16:52
Inside do_job at 15:17:52
Is there a way to specify in the cron schedule to run it at the first minute as well?
If you want the job to run immediately when you start the script and then continue running every minute, you can modify your code slightly to achieve that. Here's how you can do it:
import schedule
import time
from datetime import datetime
def do_job():
print("Inside do_job at", datetime.now().strftime("%H:%M:%S"))
print("Starting at", datetime.now().strftime("%H:%M:%S"))
do_job() # Call the job immediately when starting
schedule.every(1).minutes.do(do_job)
while True:
schedule.run_pending()
time.sleep(1) # Sleep for a short interval to avoid high CPU usage
Hope this will solve the issue.