在Python/Pyramid/CherryPy中,如何正确处理周期性维护任务?

2 投票
3 回答
1592 浏览
提问于 2025-04-18 04:43

我有一个用Python写的网页应用,使用Pyramid和CherryPy作为网络服务器。

这个应用有一些定期需要执行的维护任务,比如清理过期的会话、释放资源等等。

那么,管理这些任务的正确方法是什么呢?我可以比较简单地再开一个“维护”线程(并使用一个单独的调度器,比如APscheduler),但是让一个单独的线程去干扰正在运行的服务器线程,感觉有点笨拙。CherryPy已经在一个多线程的事件循环中运行服务器,似乎应该可以通过这个事件循环来安排定期的任务。

3 个回答

1

为了自己省事,直接用cron吧。没必要自己去写调度软件。

2

我看到@fumanchu的回答后,找到了这个答案,但最后我使用了一个叫做 cherrypy.process.plugins.BackgroundTask 的插件:

def doHousekeeping():
    print("Housekeeper!")

-

def runServer():


    cherrypy.tree.graft(wsgi_server.app, "/")

    # Unsubscribe the default server
    cherrypy.server.unsubscribe()

    # Instantiate a new server object
    server = cherrypy._cpserver.Server()

    # Configure the server object
    server.socket_host = "0.0.0.0"
    server.socket_port = 8080
    server.thread_pool = 30

    # Subscribe this server
    server.subscribe()

    cherrypy.engine.housekeeper = cherrypy.process.plugins.BackgroundTask(2, doHousekeeping)
    cherrypy.engine.housekeeper.start()

    # Start the server engine (Option 1 *and* 2)
    cherrypy.engine.start()
    cherrypy.engine.block()

这样做的结果是,doHousekeeping() 会在CherryPy的事件循环中每隔2秒被调用一次。

而且,这样做也不需要做一些很傻的事情,比如为了定期调用一个任务而把整个操作系统都拖进来。

撰写回答