I have the following function which is called from a function of a class. I would like to call this as a non blocking thread or daemon process. And I want it to be stopped gracefully taking care of any IO locks and DB locks (which happen inside foo()
).
def worker(fnames):
while True:
for f in fnames:
while(not os.path.isfile(f)):
time.sleep(SLEEP_INTERVAL)
while os.stat(f).st_size < 1000000:
time.sleep(SLEEP_INTERVAL)
file= open(f, 'rb')
#Do Something
foo()
os.remove(f)
I looked in to first answer on this link and modified the code. Do I create a driver function for the above function, run the driver function from a new thread, and pass the _stop event flag from the below thread to it? Or is there a better way?
class StoppableThread(threading.Thread):
def __init__(self, target, timeout):
super(StoppableThread, self).__init__()
self._target = target
self._timeout = timeout
self._stop = threading.Event()
def run(self):
while not self.stopped():
self._stop.wait(self._timeout) # instead of sleeping
if self.stopped():
continue
self._target()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
EDIT: I managed to think of the following solution, but I find it very nasty. Any help is appreciated:
def run(self):
while True:
for f in fnames:
while not self._stop.isSet():
while(not os.path.isfile(f)):
self._stop.wait(SLEEP_INTERVAL)
if self._stop.isSet():
break;
while os.stat(f).st_size < 1000000:
self._stop.wait(SLEEP_INTERVAL)
if self._stop.isSet():
break;
if self._stop.isSet():
continue;
file= open(f, 'rb')
#Do Something
foo()
os.remove(f)
if self._stop.isSet():
break;
if self._stop.isSet():
break;