[英]How to properly have Flask run a threaded task in background on Heroku?
所以,基本上,我有一个无限的while循环,每隔几分钟就会不断地抓取一个网站。 然而,为了启动这个过程,我只是导航到 /scraper 来启动新线程,虽然这完全正常,但我不想继续路由到 /scraper 来启动线程,如果 Heroku 重新启动他们的服务器维护。 有没有一种方法可以实现这一点,这样如果我路由到主页/我只能运行一个线程,因为我宁愿通过路由到主页而不是 /scraper 来启动爬虫。
def scrappy():
while True:
try:
print("Loading scraper...")
exec(open("texas_scraper.py").read()) #time.sleep(300) inside this .py
except Exception as e:
print("Error: There may be a bug in the code or your environment setup.")
print(e)
time.sleep(60)
continue
@app.route('/')
def index():
print("Someone is on homepage")
return '''
<html><body>
Hi. <a href="/uploads"> Please click here to download the roster.</a>
</body></html>
'''
@app.route('/scraper')
def digger():
t1 = Thread(target = scrappy)
t1.setDaemon(True)
t1.start()
print("Someone started the scraper")
return '''
<html><body>
Hi. Loading scraper now!
</body></html>
'''
您正在寻找的可能是在 Heroku 中启动两个不同的进程。
Heroku 有一个Procfile
,用于确定实际启动应用程序的内容。 一个可能是按原样启动您的网络服务器。 来源。
可以定义第二个进程,这就像在 procfile 中添加新行一样简单。 您可以使用该新行来启动Celery 之类的东西,它可以完全满足您的需求。 Celery 是一个分布式任务队列系统,您可以使用它来例如每 n 次调度一个任务。 这也将消除您的 while 循环的需要,因为您可以简单地每 300 秒安排一次。
web: flask run
worker: celery worker -A your_app/celery.py
Celery 显然还有其他替代方案,找到适合您需求的不错的任务队列框架。 你甚至可以直接运行你的 webscraper,但是,这可能不会像 Celery 在发生崩溃时那样自行恢复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.