我有一个python web-app,它使用Pyramid / CherryPy作为网络服务器。
它有一些需要运行的定期内务处理任务 - 清理陈旧的会话,释放他们的资源等......
管理此问题的正确方法是什么?我可以很容易地再运行一次"内务管理"线程(并使用单独的调度程序,如APscheduler),但有一个单独的线程到达正在运行的服务器线程似乎是一个非常笨拙的解决方案。 CherryPy已经在一个(多线程)事件循环中运行服务器,似乎应该可以以某种方式安排定期事件。
答案 0 :(得分:2)
帮自己一个忙,只需使用cron。无需推出自己的日程安排软件。
答案 1 :(得分: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()
在CherryPy事件循环中以{2}间隔调用doHousekeeping()
的结果。
它也不涉及像在整个操作系统中拖动一样愚蠢而只是定期调用任务。
答案 2 :(得分:1)