Reputation: 159
So this is something I have been wondering for a while, and while I don't know if there is a correct answer there is probably a better option.
So which of the options below is best to schedule a python script to run at a specific time? Let me know what you prefer, or if you have an alternative.
1) Take a python file script.py, write a ".bat" file to run the code in command prompt, and then use windows native task scheduler to launch the file at a specific time each day.
BAT Example:
cd C:\Users\Administrator\Documents\Scripts
python script.py
This is some code for a BAT file that will run your python script.
2) Use python to create a timed task within your file like some of the examples below:
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while 1:
schedule.run_pending()
time.sleep(1)
or
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
or
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
When it comes to option 2 there are plenty of examples I could include but I just want to know whats better in your opinion.
Does one of the options use more processing power? Is one of the options more reliable? etc.
Upvotes: 1
Views: 4084
Reputation: 31
I have never used Option 2 personally. In general, if you just have one or two servers. Task Scheduler (Windows) or cron (Linux) would be the way to go.
There are also tools like AutoSys that are built for scheduling batch jobs.
Upvotes: 1
Reputation: 562
I will choose option 1. If you choose option 2, your code will not run in several circumstances, such as your machine restart or your python IDE crashes. Option 1 will run your code as long as your machine is running.
Upvotes: 2