Python web server and periodic tasks

I use CherryPy to receive requests through the REST API. In addition to processing requests, the application must also perform some resource management every few seconds. What is the easiest way to do this?

1) run a separate thread

2) cherrypy.process.plugins.PerpetualTimer (don't know how to use it, and looks like it's heavy for resources?)

3) in any other way?

A separate thread solution is fine for me, but I was wondering if there is a better way to do this?

Please note that CherryPy is not a requirement - I decided to use it primarily because the project looks live and because it supports multiple simultaneous connections (in other words: I am open to alternatives).

+5
source share
1 answer

PerpetualTimer is just a repeating version of threading._Timer.

What you really want to use is cherrypy.process.plugins.Monitor , which is nothing more than a way to start a separate thread for you. You should use it because it connects to cherrypy.engine, which controls the start and stop behavior for CherryPy servers. If you start your own thread, you will want to stop it when the CP shuts down anyway; the Monitor class already knows how to do this. It uses PerpetualTimer under the hood, to the latest versions, where it has been replaced by the BackgroundTask class.

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

All Articles