1

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
John Lapoya
  • 582
  • 1
  • 8
  • 21
  • 2
    What does daemonizing mean in this context? Do you need to run the app in the background as it's own process or do you want `write_it()` to run "in the background" while your app does something else? – msvalkon Apr 24 '14 at 12:09
  • The idea is daemonize write_it() and be able to do something else – John Lapoya Apr 24 '14 at 12:12
  • What's the problem exactly? That thread is running in the background, and you can continue running code. – sdamashek Apr 24 '14 at 12:13
  • With your current code, write_it() is running in the background as a "daemon" - do you want to be able to run other /python/ code or do you want the program to stop (as in the python process forks)? – sdamashek Apr 24 '14 at 12:15
  • I just want to let this code running while I can do something else – John Lapoya Apr 24 '14 at 20:31

1 Answers1

1

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.

robjohncox
  • 3,639
  • 3
  • 25
  • 51