Python CherryPy具有用于自定义作业的附加线程

Python CherryPy具有用于自定义作业的附加线程,python,multithreading,daemon,cherrypy,Python,Multithreading,Daemon,Cherrypy,我们正在设计一个基于CherryPy的系统,除了服务web请求外,还需要并行执行任务/作业。我们希望它是作为守护进程运行的单个进程,并为所有并行作业(如计划任务或在线收集数据)创建线程 我浏览了CherryPy文档,知道它是线程池,为所有用户请求创建线程。然而,我似乎找不到关于如何为自定义作业创建和管理线程的文档。CherryPy是否有一个线程处理程序,我们可以钩住它,或者我们是否可以/应该编写自己的处理程序钩住CherryPy?订阅一个实例: from cherrypy.process.plu

我们正在设计一个基于CherryPy的系统,除了服务web请求外,还需要并行执行任务/作业。我们希望它是作为守护进程运行的单个进程,并为所有并行作业(如计划任务或在线收集数据)创建线程

我浏览了CherryPy文档,知道它是线程池,为所有用户请求创建线程。然而,我似乎找不到关于如何为自定义作业创建和管理线程的文档。CherryPy是否有一个线程处理程序,我们可以钩住它,或者我们是否可以/应该编写自己的处理程序钩住CherryPy?

订阅一个实例:

from cherrypy.process.plugins import Monitor

def foo():
    my.store.collect_data('things', 'stuff')

Monitor(cherrypy.engine, foo, frequency=300).subscribe()

这将在自己的线程中每300秒运行一次
foo
函数,该线程将在调用
引擎时启动。启动
并在调用
引擎时停止。停止
(或在进程退出时)。

我想通过分享我编写的脚本来完成fumanchu的出色回答,在使用它之前对其进行测试。它使用python瓶子,证明了该建议也适用于它

#!/usr/bin/env python3

import bottle
import time
import threading
import cherrypy
from cherrypy.process.plugins import Monitor

srv = bottle.Bottle()
lock = threading.Lock()
x = 0
y = 0

def increment ():
    print("incrementing...")
    with lock:
        global x
        time.sleep(1)
        x += 1
    print("Done.")

monitor = Monitor(cherrypy.engine, increment, frequency=1)

@srv.get("/")
def read ():
    with lock:
        return "Got: %d %d." % (x, y)

@srv.post("/periodic/<x:int>")
def periodic (x):
    if x: monitor.start()
    else: monitor.stop()

@srv.put("/<V:int>")
def write (V):
    print("Serving")
    with lock:
        global x
        global y
        x = V
        time.sleep(5)
        y = V
        print("gtfo")
    return "OK. Current: %d." % x

srv.run(server='cherrypy')
#/usr/bin/env蟒蛇3
进口瓶
导入时间
导入线程
进口樱桃
从cherrypy.process.plugins导入监视器
srv=瓶子。瓶子()
lock=threading.lock()
x=0
y=0
def增量():
打印(“递增…”)
带锁:
全球x
时间。睡眠(1)
x+=1
打印(“完成”)
监视器=监视器(cherrypy.engine,增量,频率=1)
@srv.get(“/”)
def read():
带锁:
返回“Got:%d%d.”%(x,y)
@srv.post(“/定期/”)
def定期(x):
如果x:monitor.start()
else:monitor.stop()
@srv.put(“/”)
def写入(V):
打印(“服务”)
带锁:
全球x
全局y
x=V
时间。睡眠(5)
y=V
打印(“gtfo”)
返回“确定。当前:%d.%x
srv.run(server='cherrypy')
用法: 启用服务器后,使用
curlhttp://localhost:8080
阅读,
curlhttp://localhost:8080/
写入一些值(需要5秒钟,而所有读取都将挂起),最后是
curlhttp://localhost:8080/periodic/0
卷曲http://localhost:8080/periodic/1
分别禁用/启用定期写入。每次写入将花费1秒,在此期间读取和修改将挂起

注意:在我的例子中,使用蟒蛇2和蟒蛇3的kwarg“间隔”应该是“频率”。