So I have some threads in an application that monitor a temporarily available file on some 3rd party endpoint. I want them to perform their purpose in life for no more than a day, then terminate. What's the best way to do that?
There are lots of questions on S/O about making a thread terminate if it times out on some function (like a TCP hangs connection or something) but my goal centers more around giving the thread a lifespan independent of the functions it performs. I whipped up a quick demo of what i'm thinking so far:
class Task(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.life = datetime.utcnow() + timedelta(seconds=60)
def run(self):
while True:
if datetime.utcnow() < self.life:
#do stuff that i do
print "hi"
time.sleep(5)
else:
break
t = Task()
t.start()
This works fine but am I thinking about this in a dumb way? Is there a better way to handle it?