每隔n秒做一次没有while循环的事情?

时间:2012-11-01 17:34:14

标签: python while-loop freeze blender

好吧,我正在尝试为Blender编写一个附加组件,我需要每隔n秒做一次,但是,我不能使用while循环,因为它冻结了Blender!我该怎么办?

4 个答案:

答案 0 :(得分:3)

from threading import Timer

def doSomeThings():
    print "Things are being done"

t = Timer(5.0, doSomeThings)  # every 5 seconds
t.start()

答案 1 :(得分:1)

来自Blender API文档的Strange errors using ‘threading’ module

  

使用Blender的Python线程仅在脚本完成之前完成线程时才能正常工作。例如,使用threading.join()。

     

注意:Pythons线程只允许共同货币,不会加速多处理器系统上的脚本,子进程和多进程模块可以与blender一起使用,也可以使用多个CPU

from threading import Thread, Event

class Repeat(Thread):
    def __init__(self,delay,function,*args,**kwargs):
        Thread.__init__(self)
        self.abort = Event()
        self.delay = delay
        self.args = args
        self.kwargs = kwargs
        self.function = function
    def stop(self):
        self.abort.set()
    def run(self):
        while not self.abort.isSet():
            self.function(*self.args,**self.kwargs)
            self.abort.wait(self.delay)

示例:

from time import sleep
def do_work(foo):
    print "busy", foo
r = Repeat(1,do_work,3.14) # execute do_work(3.14) every second
r.start() # start the thread
sleep(5)  # let this demo run for 5s
r.stop()  # tell the thread to wake up and stop
r.join()  # don't forget to .join() before your script ends

答案 2 :(得分:1)

根据您的需要,time.sleepthreading.Timer可能会完成这项工作。

如果您需要更全面的调度程序,我最喜欢的版本是在http://code.activestate.com/recipes/496800-event-scheduling-threadingtimer/找到的食谱:

import thread
import threading

class Operation(threading._Timer):
    def __init__(self, *args, **kwargs):
        threading._Timer.__init__(self, *args, **kwargs)
        self.setDaemon(True)

    def run(self):
        while True:
            self.finished.clear()
            self.finished.wait(self.interval)
            if not self.finished.isSet():
                self.function(*self.args, **self.kwargs)
            else:
                return
            self.finished.set()

class Manager(object):

    ops = []

    def add_operation(self, operation, interval, args=[], kwargs={}):
        op = Operation(interval, operation, args, kwargs)
        self.ops.append(op)
        thread.start_new_thread(op.run, ())

    def stop(self):
        for op in self.ops:
            op.cancel()

class LockPrint(object):
    def __init__(self):
        self.lock = threading.Lock()
    def lprint(self, value):
        with self.lock:
            print value

if __name__ == '__main__':
    import time
    import datetime

    lp = LockPrint()

    def hello1():
        lp.lprint('{}\thello1!'.format(datetime.datetime.now()))
    def hello2():
        lp.lprint('{}\thello2!'.format(datetime.datetime.now()))
    def hello3_blocking(): # this is bad, so don't do it in real code ;)
        lp.lprint('{}\thello3_blocking starting... '.format(
            datetime.datetime.now()
        )),
        t = time.time() # get a timestamp
        x = 0
        while time.time() - t < 3: # iterate in a blocking loop for 3 secs
            x += 1
        lp.lprint('{}\thello3_blocking complete! ({} iterations)'.format(
            datetime.datetime.now(), x
        ))



    timer = Manager()
    timer.add_operation(hello1, 1)
    timer.add_operation(hello2, 2)
    timer.add_operation(hello3_blocking, 2)

    t0 = time.time()
    while time.time() - t0 < 10:
        time.sleep(0.1)
    # turn off everything and exit...
    timer.stop()

这通常是时间安全的,因为每个操作都在一个线程下执行,主线程仍然可以切换出各个操作线程中的阻塞部分,并维护其他操作的时间表(假设你的功能不是不要一直提到解释器的任何异常,打破主调度程序线程......)

我不确定这会如何与blender一起使用,但它在我使用的其他环境(特别是基于龙卷风的服务器)的非阻塞模式下运行良好。

答案 3 :(得分:-1)

import threading

def hello():
   print "hello, world"
   t = threading.Timer(30.0, hello)
   t.start() # after 30 seconds, "hello, world" will be printed

我对python不是很好,并没有尝试过这个。看看这有助于你:)