Search code examples
javascriptprocesskillcherrypy

CherryPy kill process if not pinged in time


Is there a way to have CherryPy (running on :8080, it's only function being a listener for SIGUSR1) kill a process if it hasn't been pinged in a certain number of seconds?

Certainly the Python code for process killing is not in question, simply the way CherryPy would detect the last ping, and constantly compare it to the current time - Killing a process if it hasn't been pinged in a certain number of seconds.

Note that if Javascript is doing the pinging (via setInterval()), an infinite loop within the CherryPy code would cause the .ajax() request to hang and/or timeout, unless there is a way to have .ajax() only ping and not wait for any type of response.

Thanks for any tips you guys can provide!

Mason


Solution

  • Ok, so the answer was to set up two classes, one that updates the time, the other that constantly checks if the timestamp hasn't been updated in 20 seconds. This is ULTRA useful when it comes to killing a process once your user leaves a page, if the entire site isn't built on CherryPy. In my case, it is simply sitting on :8080 listening for JS pings from a Zend project. The CherryPy code looks like:

    import cherrypy
    import os
    import time
    
    class ProcKiller(object):
    
        @cherrypy.expose
        def index(self):
            global var 
            var = time.time()
    
        @cherrypy.expose
        def other(self):
            while(time.time()-var <= 20):
                time.sleep(1)
            print var
            os.system('pkill proc')     
    
    
    cherrypy.quickstart(ProcKiller())
    

    The JS that pings is literally as simple as:

    <script type="text/javascript">
    function ping(){
        $.ajax({
           url: 'http://localhost:8080'
        });
     }
    function initWatcher(){
        $.ajax({
           url: 'http://localhost:8080/other'
        });
     }
    
    ping(); //Set time variable first
    initWatcher(); //Starts the watcher that waits until the time var is >20s old
    setInterval(ping, 15000); //Updates the time variable every 15s, so that while users are on the page, the watcher will never kill the process
    </script>
    

    Hope that this helps someone else looking for a similar solution to process killing once users leave a page!

    Mason