【问题标题】:Flask + uwsgi + threading烧瓶 + uwsgi + 线程
【发布时间】:2018-02-02 12:35:54
【问题描述】:

我有一个烧瓶应用程序,我想通过线程每分钟执行一次更新任务。

线程是这样设置的:

def print_thread():
    print "I am a thread"

@app.before_first_request
def start_thread():
    threading.Timer(60, print_thread).start()

flask 应用程序正在通过uwsgi 运行:

uwsgi_python -s /tmp/uwsgi.sock --processes 1 --threads 4 -w app:app --enable-threads

我之前遇到过这个问题,并通过flask 端点解决了这个问题,该端点每分钟通过cron 调用一次,但我想要一个更干净的解决方案,它是自包含在flask 应用程序中的。

谁能找出问题所在?

或者知道解决这个问题的干净解决方案吗?

谢谢

【问题讨论】:

    标签: python multithreading flask uwsgi


    【解决方案1】:

    我建议避免在与通过 WSGI 创建的烧瓶实例相同的进程中运行后台任务。这让您可以确保通过 uwsgi 创建的多个进程\线程不会重复后台任务。

    您可以从不同的文件启动单独的 python 进程并使用 python 调度,例如,apscheduler

    from apscheduler.schedulers.background import BlockingScheduler
    
    from app import create_app # Your app factory
    from app import job # A job function
    
    # Most probably, your background job will depend on your app being initialized
    # If you don't use the app factory pattern, you can simply import a file containing your app to trigger initialization. 
    app = create_app() 
    
    scheduler = BlockingScheduler()
    scheduler.add_job(job, 'interval', minutes=1)
    
    scheduler.start()
    

    然后您可以将此脚本放在您的 app.py 旁边并使用以下命令启动一个进程 python your_name.py 并让它与 uwsgi 一起运行。这样,您的网络应用程序和后台任务将共享代码和配置,但进程将明确分开。

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 2013-09-01
      • 2021-09-10
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多