如何在Heroku中运行后台任务?

编程入门 行业动态 更新时间:2024-10-10 04:21:21
本文介绍了如何在Heroku中运行后台任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经构建了一个python应用程序,并使用 Flask 和 Python 进行了部署.这是我的代码的斯凯尔顿.

I have already build a a python app and deployed it using Flask and Python. Here is my Skelton of my code.

#app.py @app.route('/', methods=['GET']) def login(): '''login process''' @app.route('/reset-password', methods=['GET']) def reset_password(): '''reset password process''' @app.route('/add-psa', methods=['GET']) def add_user(): '''add user process''' if __name__ == '__main__': app.debug = True app.run(use_reloader=False, threaded=True)

已部署的应用程序在Heroku中工作正常.但是根据Heroku 文档.因此,我遵循了此教程来运行后台作业.这是我到目前为止所做的

Deployed app work fine in the Heroku. But sometime it takes more than 30 seconds to response which means H12 error according to Heroku doc. So I followed this tutorial to run background job. Here is what I've done so far

#worker.py import os import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work()

下一步...

#utils.py import requests def count_words_at_url(url): resp = requests.get(url) return len(resp.text.split())

我还更改了 Procfile 和 requirements.txt

我想在后台运行我的 reset_password(),因为它花费的时间超过 30秒.有人可以帮助我吗?

I want to run my reset_password() in background since its taking more than 30seconds. Any one who can help me on this?

推荐答案

一种解决方案是从Web请求中生成线程:在这种情况下,可以在后台线程启动并执行必要的操作时立即(几乎)返回响应.任务(不受HTTP超时限制)

A solution is to spawn a thread from the web request: in this case the response can be returned (almost) immediately while a background thread starts and performs the necessary task (without the constraint of the HTTP timeout)

# my background thread class MyWorker(): def __init__(self, message): self.message = message thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): logging.info(f'run MyWorker with parameter {self.message}') # do something

Web请求创建线程的实例,并可以通知调用方正在进行的操作(或应用其他工作流/消息)

The web request creates an instance of the thread and could inform the caller something is in progress (or apply a different workflow/message)

#app.py @app.route('/reset-password', methods=['GET']) def reset_password(): '''reset password process''' MyWorker('param_value') return "In progress... You will receive an email"

更多推荐

如何在Heroku中运行后台任务?

本文发布于:2023-10-12 16:23:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485263.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   如何在   Heroku

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!