Efficient Python Daemon

Kyle Hotchkiss picture Kyle Hotchkiss · Jan 9, 2011 · Viewed 53.9k times · Source

I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case?

I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that.

Answer

aculich picture aculich · Dec 4, 2011

Rather than writing your own daemon, use python-daemon instead! python-daemon implements the well-behaved daemon specification of PEP 3143, "Standard daemon process library".

I have included example code based on the accepted answer to this question, and even though the code looks almost identical, it has an important fundamental difference. Without python-daemon you would have to use & to put your process in the background and nohup and to keep your process from getting killed when you exit your shell. Instead this will automatically detach from your terminal when you run the program.

For example:

import daemon
import time

def do_something():
    while True:
        with open("/tmp/current_time.txt", "w") as f:
            f.write("The time is now " + time.ctime())
        time.sleep(5)

def run():
    with daemon.DaemonContext():
        do_something()

if __name__ == "__main__":
    run()

To actually run it:

python background_test.py

And note the absence of & here.

Also, this other stackoverflow answer explains in detail the many benefits of using python-daemon.