开发者

python web server and periodic tasks

开发者 https://www.devze.com 2023-04-11 04:21 出处:网络
I am using CherryPy to receive requests through REST API. Apart from handling requests the application should also do some resource management every few seconds. What is the easiest way to do this?

I am using CherryPy to receive requests through REST API. Apart from handling requests the application should also do some resource management every few seconds. What is the easiest way to do this?

1) run a separate thread

2) cherrypy.process.plugins.PerpetualTimer (not sure how to use it, and it looks like it is heavy on resources?)

3) some other way?

The solution with a separate thread is fine by me, but I was wondering if there is a nicer way to do it?

Note that CherryPy is not a requirement - I have decided to use it primarily because the project looks alive and because it supports multiple开发者_StackOverflow中文版 simultaneous connections (in other words: I am open to alternatives).


PerpetualTimer is just a repeating version of threading._Timer.

What you really want to use is cherrypy.process.plugins.Monitor, which is little more than a way to run a separate thread for you. You should use it because it plugs into cherrypy.engine, which governs start and stop behavior for CherryPy servers. If you run your own thread, you're going to want to have it stop when CP shuts down anyway; the Monitor class already knows how to do that. It uses PerpetualTimer under the hood, until recent versions, where it was replaced by the BackgroundTask class.

my_task_runner = Monitor(cherrypy.engine, my_task, frequency=3)
my_task_runner.subscribe()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号