所以这是我一直想知道的事情,虽然我不知道是否有正确答案,但可能有更好的选择。
那么下面哪个选项最适合安排 python 脚本在特定时间运行?让我知道您喜欢什么,或者您是否有其他选择。
1) 获取一个 python 文件 script.py,编写一个“.bat”文件以在命令提示符下运行代码,然后使用 Windows 原生任务计划程序在每天的特定时间启动该文件。
BAT 示例:
cd C:\Users\Administrator\Documents\Scripts
python script.py
这是将运行 python 脚本的 BAT 文件的一些代码。
2) 使用 python 在您的文件中创建定时任务,如下面的一些示例:
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)
或
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()
或
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'])
关于选项 2,我可以举出很多示例,但我只想知道您认为哪个更好。
其中一个选项是否使用更多处理能力?其中一个选项更可靠吗?等
最佳答案
我会选择选项 1。如果您选择选项 2,您的代码将在多种情况下无法运行,例如您的机器重启或您的 Python IDE 崩溃。 只要您的机器正在运行,选项 1 就会运行您的代码。
关于python - 通过任务计划程序或代码在需要时运行来安排 python 脚本更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48107347/