Search code examples
pythondaemon

Efficient Python Daemon


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.


Solution

  • I think your idea is pretty much exactly what you want. For example:

    import time
    
    def do_something():
        with open("/tmp/current_time.txt", "w") as f:
            f.write("The time is now " + time.ctime())
    
    def run():
        while True:
            time.sleep(60)
            do_something()
    
    if __name__ == "__main__":
        run()
    

    The call to time.sleep(60) will put your program to sleep for 60 seconds. When that time is up, the OS will wake up your program and run the do_something() function, then put it back to sleep. While your program is sleeping, it is doing nothing very efficiently. This is a general pattern for writing background services.

    To actually run this from the command line, you can use &:

    $ python background_test.py &
    

    When doing this, any output from the script will go to the same terminal as the one you started it from. You can redirect output to avoid this:

    $ python background_test.py >stdout.txt 2>stderr.txt &