0

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?

Community
  • 1
  • 1
ericksonla
  • 1,247
  • 3
  • 18
  • 34
  • I'm wondering if you considered about using Cron here. – Philip Tzou Jan 26 '17 at 22:25
  • I've considered it, but my main program has too start and stop `bar` every couple days or so. Using python to set up Cron seems ugly too (but I've never used Cron much). But I'm open to suggestions if you can think of a clean way to do it. – ericksonla Jan 26 '17 at 22:29
  • 1
    I'm thinking about a flag (perhaps a file) that your Python program can easily set and the program run by Cron can also easily use the existence of the file to determine if it should proceed. – Philip Tzou Jan 26 '17 at 22:43
  • @Philip Tzou I was just typing in a similar answer. That is what I would do. – RobertB Jan 26 '17 at 22:50

0 Answers0