简体   繁体   English

Heroku 多线程

[英]Heroku multi-threading

I am making a website with heroku and now I'm making a task that will run in the background我正在使用 heroku 制作一个网站,现在我正在制作一个将在后台运行的任务
Something like this:像这样的东西:

def task():
    while True:
        ...
        # some task that will run in the background

And in my file app.py , I have this code:在我的文件app.py中,我有以下代码:

if __name__ == "__main__":
    Thread(target=app.run).start()
    Thread(target=task).start()

I've put some print in the task function (something like print("Task started")我在任务 function 中放了一些print (类似于print("Task started")
But in the heroku log I only saw flask started message and no task message, not even an error, and the things that should happen in the task function doesn't happen.但是在 heroku 日志中,我只看到 flask 启动消息,没有任务消息,甚至没有错误,并且任务 function 中应该发生的事情没有发生。 And I try to run the flask app in my local machine and it works.我尝试在我的本地机器上运行 flask 应用程序,它可以工作。

So how to fix this?那么如何解决这个问题呢?

The "correct" way to do this on Heroku is to define your background task as a separate process, eg by doing something like this in your Procfile :在 Heroku 上执行此操作的“正确”方法是将后台任务定义为单独的进程,例如在Procfile中执行以下操作:

web: gunicorn app:app
worker: python path/to/background_task.py

Now you can scale up a dyno to run the worker process:现在您可以扩展测功机来运行worker进程:

heroku ps:scale worker=1

There are lots of benefits to this approach , but it does mean you need to have at least two dynos running.这种方法有很多好处,但这确实意味着您需要至少运行两个测功机。 That either costs money or consumes free dyno hours at a faster rate.这要么花钱,要么以更快的速度消耗免费的测功时间。

Try rewriting your code so that it looks like this:尝试重写您的代码,使其看起来像这样:

if __name__ == "__main__":
    Thread(target=task).start()
    app.run()

There's no need to start two new threads: you want your background task in a separate thread, certainly, but your flask app should just run in the main thread (what else is the main thread going to do?).无需启动两个新线程:当然,您希望后台任务在单独的线程中,但您的 flask 应用程序应该只在主线程中运行(主线程还要做什么?)。

I'm not certain this is your problem, so I'm curious to know how it works out.我不确定这是你的问题,所以我很想知道它是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM