Question

I need to work this script in background like daemon, till now i just could it make work but not in background:

import threading
from time import gmtime, strftime
import time


def write_it():
    #this function write the actual time every 2 seconds in a file
    threading.Timer(2.0, write_it).start()
    f = open("file.txt", "a")
    hora = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    #print hora
    f.write(hora+"\n") 
    f.close()

def non_daemon():
    time.sleep(5)
    #print 'Test non-daemon'
    write_it()

t = threading.Thread(name='non-daemon', target=non_daemon)

t.start()

I already tried another ways but no of them work in background as I was looking, any other alternative?

Was it helpful?

Solution

If you are looking to run the script as a daemon, one good approach would be to use the Python Daemon library. The code below should do what you are looking to achieve:

import daemon
import time

def write_time_to_file():
    with open("file.txt", "a") as f:
        hora = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        f.write(hora+"\n")

with daemon.DaemonContext():
    while(True):
        write_time_to_file()
        time.sleep(2)

Tested this locally and it worked fine, appending time to the file every 2 seconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top