I have a thread in my process that has a few characteristics: 1. it mostly sleeps 2. it only toggles a few booleans; it doesn't interact with any data that could be messed up from abrupt killing (eg, an external database) 3. it may need to be killed at any time from another thread.
A rough approximation is:
import time
import threading
class Foo():
def __init__(self):
self.my_bool = True
def bar(self):
while True:
time.sleep(60*30)
self.my_bool = not self.my_bool
foo = Foo()
t = threading.Thread(target=foo.bar)
t.start()
According to this highly voted question/answer, I should not kill it abruptly. Does this still apply since it clearly isn't going to be ruining my data collection and cleanup? Specifically, in my kill function, I will manually clean up the processes that interact with the boolean.
I can imagine some other options such as this:
import time
import threading
import datetime
class Foo():
def __init__(self):
self.my_bool = True
self.killed = False
def bar(self):
while True and not self.killed:
next_toggle_time = datetime.datetime.now() + datetime.timedelta(minutes=15)
print 'next toggle time: ', next_toggle_time
while datetime.datetime.now() < next_toggle_time and not self.killed:
time.sleep(0.1)
self.my_bool = not self.my_bool
This doesn't appear to use much memory (0.1% of a MacBook Pro) but it feels kind of ugly and I'm planning to use this on computers with much more limited memory. Is there a better way?