【问题标题】:How to make a python script to run only on specific time on Heroku?如何使 python 脚本仅在 Heroku 上的特定时间运行?
【发布时间】:2020-11-08 20:18:58
【问题描述】:
我有一个 python 脚本(使用selenium 执行操作并将结果发送到我的what'sapp [Used Twilio API])并且我将它托管在Heroku 上并计划运行one time per day。它按预期在预定时间运行,但也在其他时间运行(每天超过 6 次)。我不想在预定时间以外运行它。我怎样才能让它只在预定的时间运行?
Procfile:
web: python my_script.py
除此之外,我的目录中还有requirements.txt & my_script.py。
【问题讨论】:
标签:
python
selenium
heroku
procfile
【解决方案1】:
您可以使用time 模块和while 循环来检查当前时间是否等于您想要的时间。
from time import gmtime, strftime
desired_time = '13:28'
while True:
if strftime("%H:%M", gmtime()) == desired_time:
main()
【解决方案2】:
提供的答案可能是最简单的选项。这是我在个人项目中使用的。
您可以使用APScheduler 来安排任务以某个时间间隔运行。
from apscheduler.schedulers.background import BackgroundScheduler
def start():
scheduler = BackgroundScheduler()
scheduler.add_job(my_logger, 'interval', seconds=3)
scheduler.start()