简体   繁体   中英

Running scheduled task in python

I have a python script where a certain job needs to be done at say 8 AM everyday. To do this what i was thinking was have a while loop to keep the program running all the time and inside the while loop use scheduler type package to specify a time where a specific subroutine needs to start. So if there are other routines which run at different times of the day this would work.

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("08:00").do(job,'It is 08:00')

Then let windows scheduler run this program and done. But I was wondering if this is terribly inefficient since the while loop is waste of cpu cycles and plus could freeze the computer as the program gets larger in future. Could you please advise if there is a more efficient way to schedule tasks which needs to executed down to the second at the same time not having to run a while loop ?

I noted that you have a hard time requirement for executing your script. Just set your Windows Scheduler to start the script a few minutes before 8am. Once the script starts it will start running your schedule code. When your task is done exit the script. This entire process will start again the next day.

and here is the correct way to use the Python module schedule

from time import sleep
import schedule


def schedule_actions():

  # Every Day task() is called at 08:00
  schedule.every().day.at('08:00').do(job, variable="It is 08:00")

  # Checks whether a scheduled task is pending to run or not
  while True:
    schedule.run_pending()

    # set the sleep time to fit your needs
    sleep(1)


def job(variable):
    print(f"I'm working...{variable}")
    return


schedule_actions()

Here are other answers of mine on this topic:

Why a while loop? Why not just let your Windows Scheduler or on Linux cron job run your simple python script to do whatever, then stop?

Maintenance tends to become a big problem over time, so try to keep things as lightweight as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM