用threading 解决 gunicorn worker timeout

布满荆棘的人生 2021-12-14 03:37 312阅读 0赞

产生worker timeout 的背景

  1. while 1:
  2. .....
  3. time.sleep(1)
  4. gunicorn运行起来,只等待了30s,就卡住了,没报任何异常或err,查了gunicorn 官方文档,原来是线程默认等待30s kill 掉,再restart
  5. http://docs.gunicorn.org/en/stable/settings.html

timeout

  • -t INT, --timeout INT
  • 30

Workers silent for more than this many seconds are killed and restarted.

Generally set to thirty seconds. Only set this noticeably higher if you’re sure of the repercussions for sync workers. For the non sync workers it just means that the worker process is still communicating and is not tied to the length of time required to handle a single request.

  1. 根本原因找到了,在gunicorn启动加了--timeout 120 ,还是超过30s worker timeout.搜了一圈stack没发现好的解决方法。
  2. 解决这个问题,目前最好的方法,就是在程序改代码,原先是主线程调用,用threading包装一下
  3. 如:
  4. import threading
  5. t = threading.Thread(name = '', target = func ,kwargs\{\})
  6. t.daemon = True
  7. t.start()
  8. t = threading.Thread(name='result\_package', target=result\_package, args=(pack\_name, task, issue))
  9. t.daemon = True
  10. t.start()
  11. 这样就在主线程下,把方法包装起来。
  12. 顺便用
  13. Event().wait(15) 替代 time.sleep(16)
  14. 这样写法的好处是不占用cpu,释放!

#

  1. 刚开始,分析原因花了不少时间,几行代码就把worker timeout解决了。之前试了map.thread不行。
  2. 准备用队列(celery+redis)替代原来的逻辑,只是工作量有点大,太重了。

转载于:https://www.cnblogs.com/ExMan/p/10899823.html

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Gunicorn

    Gunicorn(绿色独角兽)是一个Python WSGI的HTTP服务器。从Ruby的独角兽(Unicorn )项目移植。该Gunicorn服务器与各种Web框架兼容,实现非