用延迟调用函数的python decorator

时间:2011-03-05 18:46:39

标签: python timer

为什么这段代码不起作用?

from threading import Timer

def delayed(seconds):
    def decorator(f):
        def wrapper(*args, **kargs):
            Timer(seconds, f, args, kargs)
        return wrapper
    return decorator

@delayed(1)
def foo():
    '''this function does not return'''
    print('foo')

foo()
print('dudee')

我除了这个结果:     dudee     FOO

我只有     dudee

1 个答案:

答案 0 :(得分:5)

因为你没有启动你的计时器尝试这样:

from threading import Timer

def delayed(seconds):
    def decorator(f):
        def wrapper(*args, **kargs):
            t = Timer(seconds, f, args, kargs)
            t.start()
        return wrapper
    return decorator

@delayed(1)
def foo():

    print('foo')

foo()
print('dudee')