简体   繁体   中英

Cron Restarting A Python Daemon

I've got a simple daemon script:

#!/usr/bin/python
from myClass import theClass
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print 'run'
            classObj = theClass()
            classObj.run()

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

I can start this in Terminal with: python ./myDaemon.py start

Every once in a while it poops out for whatever reason. So, inside myClass I write a file each time it runs successfully. With another script running off of a cron eg; 1 * * * * python checkFile.py I see if the last time the script ran successfully was > 300 seconds ago. If it IS greater than I attempt to restart my daemon. This is where I'm having trouble.

When I start the daemon in my terminal window with: python ./myDaemon.py start I can close the window and go about my business and the daemon will continue to run. However, (this is where I am less understanding) if I attempt to start myDaemon.py from within my checkFile.py script using either os.system('python ./myDaemon.py start > /dev/null') or using subprocess:

proc = subprocess.Popen(['python','myDaemon.py','start'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = proc.communicate()

I am having no success. I ran checkFile.py manually from my terminal window and saw myClass output (even though I assumed the aforementioned system and subprocess commands should have suppressed that). So, the daemon starts, but if I close that window, the daemon stops.

Am I going about this wrong?

Better use daemon managers

The concept can be much simpler then:

  • all your (program) script run in foreground (daemonizing is forbidden)
  • daemonization is controlled by some daemon manager.

Popular daemon managers are:

  • zdaemon - great for running simple script
  • supervisor - great for running multiple scripts concurrently

Both are giving you a chance to require autorestart of controlled scripts in case they stop running.

Both are also allowing to capture content printed by your script to stdout and stderr and keep them in log file.

As a result, your program script will be much simpler and will focus on the task to do. The repeated task to keep them running will be left to solutions, which are in place and debugged couple of years longer than your scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM