2015-10-05 121 views
0

我一直在寻找一种方式来运行一个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') 

我虽然读许多stackoverflow线程和7个完整的教程到目前为止包括Gevent,线程,芹菜,rabbitmq,redis和不知道我应该用什么来实现这种能力。 Celery,RabbitMQ和Redis对于运行这一个后台任务似乎都非常困难和矫枉过正,再加上如果可能的话,我宁愿在Python标准库中保留选项。

到目前为止我发现的教程从非常基本的开始,然后突然跳跃到包括第三方库,套接字,特定的web框架等。是否没有办法在Python线程模块上这样做?

+0

芹菜的RabbitMQ和Redis的不是疯狂的困难。他们可能会或可能不会为你的情况矫枉过正,这取决于你的需求的细节。 – scytale

+0

@scytale。好吧,也许不是非常困难,但在尝试了大量教程和这些软件包的入门指南之后,它们最引人注目的一个基本介绍,它带有比所需更复杂的示例代码。对于一个没有这样做的例子,在两个段落中清楚地解释了一个概念(队列/列表解释),请看这里:[Multithreading/Queues](http://www.troyfawkes.com/learn-python-multithreading-queues -basics /) – zilog6502

+0

本教程针对的是熟悉基本编程概念的程序员 - 他们无法解释_everything_ - 您只需要做更多的阅读 – scytale

回答

1

你可以用multiprocessing做到这一点:

from multiprocessing import Queue, Process 

def processor(): 
    setproctitle('%s - processor ' % (__file__,)) 

    while True: 
     time.sleep(1) 
     do_stuff() 

my_processor = Process(target=processor) 
+0

就在我尝试整合之前,我假设我可以将my_processor调用粘贴到我的Bottle应用程序代码的顶部,并且它不会阻止其他应用程序与Gevent一起运行? – zilog6502

+0

是的,它应该没问题 - 你不会在'my_processor'中使用gevent,对吧? – scytale

+0

,你需要添加一些代码来清理你的主循环退出时的工作人员 – scytale