1

I'm running Python 3.3.2, Win7/Pro, 64-bit and have some code in which I'm trying to run a scheduler in its own thread. It appears that when the scheduler empties its working queue, it goes idle and does not resume even when a new entry is added to the queue. It's not completely obvious to me from the docs that it is supposed to resume, but I would not expect user code (running in a thread outside the control of the scheduler) to have to worry about the possibility of that the scheduler has "finished". I suspect there is something I'm not understanding and/or that I'm misusing it somehow, but I don't know where.

In the example below, I solved the problem by replacing the scheduler's enter method with my own which checks the queue length and if it is zero, enters the request and then calls the scheduler's run method again. This does seem to work, but definitely feels wrong. Is there something I'm missing?

class A(threading.Thread):
    def __init__(self):
        super().__init__()
        self.schedControl = sched.scheduler(time.time, time.sleep)
        self.senter = self.schedControl.enter
        self.schedControl.enter = self.enter
    def print_time(self, a=''):
        """Print current time and optional message."""
        tmx = time.time()
        tms = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(tmx))
        print("{0}:  {1}".format(tms, a))
    def run(self):
        #for call by thread's start method
        self.schedControl.run()

    def enter(self, *args, **kwargs):
        tmp = False
        if len([x for x in self.schedControl.queue]) == 0:
            tmp = True
        self.senter(*args, **kwargs)
        if tmp:
            print("Restart")
            self.schedControl.run()

class B(object):
    def __init__(self):
        self.scheduler = A()
        self.itemCount = 0
        self.scheduler.schedControl.enter(1, 1, self.scheduler.print_time, argument=('Starting Scheduler',))
        self.scheduler.start()

    def newItem(self):
        self.scheduler.schedControl.enter(1, 1, self.scheduler.print_time, argument=('New Item: {0}'.format(self.itemCount),))
        self.itemCount += 1
foo = B()
foo.newItem()
time.sleep(5)
foo.newItem()
time.sleep(5)
foo.newItem()
time.sleep(5)
foo.newItem()
time.sleep(5)
foo.newItem()
print("Going to sleep")
time.sleep(100)
sys.exit()
4

1 回答 1

0

根据文档sched将运行所有预定的事件run()。文字有点晦涩,但我相信run()一旦所有预定事件完成,就会返回。如果是这种情况,您将需要添加更多事件并run()再次调用,并给出您报告的结果,这似乎是正在发生的事情。

于 2013-07-31T17:13:13.067 回答