[英]How to run Python script only during certain hours of the day?
I've got a script that I need to run between 7am and 9pm. 我有一个脚本需要在早上7点到晚上9点之间运行。 The script already runs indefinitely but if I am able to maybe pause it outside the above hours then that'd minimize the amount of data it would produce.
该脚本已经无限期地运行,但如果我能够在上述时间之外暂停它,那么它将最小化它将产生的数据量。
I currently use time.sleep(x)
in some sections but time.sleep(36000)
seems a bit silly? 我目前在某些部分使用
time.sleep(x)
但time.sleep(36000)
似乎有点傻吗?
Using Python 2.7 使用Python 2.7
Thanks in advance! 提前致谢!
You should use cron jobs (if you are running Linux
). 您应该使用cron作业(如果您正在运行
Linux
)。
Eg: To execute your python
script everyday between 7 am and 9 am. 例如:每天早上7点到9点执行你的
python
脚本。
0 7 * * * /bin/execute/this/script.py
Now say you want to exit the program at 9 am . 现在说你想在上午9点退出该计划。
You can implement your python code like this so that it gets terminated automatically after 2 hours. 您可以像这样实现您的python代码,以便在2小时后自动终止。
import time
start = time.time()
PERIOD_OF_TIME = 7200 # 120 min
while True :
... do something
if time.time() > start + PERIOD_OF_TIME : break
You should look into using a scheduler like cron. 您应该考虑使用像cron这样的调度程序。 However, if the script is going to run indefinitely, I think
time.sleep(36000)
is acceptable (or time.sleep(10*60*60)
). 但是,如果脚本将无限期运行,我认为
time.sleep(36000)
是可接受的(或time.sleep(10*60*60)
)。
You could use the time functions to check what time of day it is, then call your script when you need to: 您可以使用时间函数来检查它的时间,然后在需要时调用脚本:
import time
import subprocess
process = None
running = False
while True:
if time.daylight and not running:
# Run once during daylight
print 'Running script'
process = subprocess.Popen("Myscript.py")
running = True
elif not time.daylight and running:
# Wait until next day before executing again
print 'Terminating script'
process.kill()
running = False
time.sleep(600) # Wait 10 mins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.