长期运行的后台任务
问题描述:
我一直在寻找一种方式来运行一个Python应用程序瓶,而同时使用GEVENT处理请求连续后台任务:长期运行的后台任务
from gevent import monkey; monkey.patch_all()
from time import sleep
from bottle import route, run
# run_background_function()
# ^^^^ starts a single background task that runs every few seconds
# and continues for the life of the whole Bottle application.
@route('/simple-request')
def simple_request():
# a simple function that returns a rendered page and
# is capable of serving multiple requests
return rendered_page()
run(host='0.0.0.0', port=8080, server='gevent')
我虽然读许多*线程和7个完整的教程到目前为止包括Gevent,线程,芹菜,rabbitmq,redis和不知道我应该用什么来实现这种能力。 Celery,RabbitMQ和Redis对于运行这一个后台任务似乎都非常困难和矫枉过正,再加上如果可能的话,我宁愿在Python标准库中保留选项。
到目前为止我发现的教程从非常基本的开始,然后突然跳跃到包括第三方库,套接字,特定的web框架等。是否没有办法在Python线程模块上这样做?
答
你可以用multiprocessing
做到这一点:
from multiprocessing import Queue, Process
def processor():
setproctitle('%s - processor ' % (__file__,))
while True:
time.sleep(1)
do_stuff()
my_processor = Process(target=processor)
芹菜的RabbitMQ和Redis的不是疯狂的困难。他们可能会或可能不会为你的情况矫枉过正,这取决于你的需求的细节。 – scytale
@scytale。好吧,也许不是非常困难,但在尝试了大量教程和这些软件包的入门指南之后,它们最引人注目的一个基本介绍,它带有比所需更复杂的示例代码。对于一个没有这样做的例子,在两个段落中清楚地解释了一个概念(队列/列表解释),请看这里:[Multithreading/Queues](http://www.troyfawkes.com/learn-python-multithreading-queues -basics /) – zilog6502
本教程针对的是熟悉基本编程概念的程序员 - 他们无法解释_everything_ - 您只需要做更多的阅读 – scytale