猿问

用Python执行周期性动作

用Python执行周期性动作

我在做Windows的工作。我想执行一个函数Foo()每10秒一次。

我该怎么做?


慕田峪4524236
浏览 1160回答 3
3回答

千巷猫影

奇怪的是,没有找到一个解决方案使用发电机来计时。我只是为了自己的目的设计了这个。这个解决方案:单线程,没有对象实例化每一个周期,使用生成器的次数,岩石固体计时下降到精确的time模块(与我从堆栈交换中尝试过的几种解决方案不同)。注:对于Python2.x,替换next(g)下面有g.next().import timedef do_every(period,f,*args):    def g_tick():        t = time.time()        count = 0        while True:            count += 1            yield max(t + count*period - time.time(),0)    g = g_tick()    while True:        time.sleep(next(g))        f(*args)def hello(s):    print('hello {} ({:.4f})'.format(s,time.time()))    time.sleep(.3)do_every(1,hello,'foo')例如:hello foo (1421705487.5811)hello foo (1421705488.5811)hello foo (1421705489.5809)hello foo (1421705490.5830)hello foo (1421705491.5803)hello foo (1421705492.5808)hello foo (1421705493.5811)hello foo (1421705494.5811)hello foo (1421705495.5810)hello foo (1421705496.5811)hello foo (1421705497.5810)hello foo (1421705498.5810)hello foo (1421705499.5809)hello foo (1421705500.5811)hello foo (1421705501.5811)hello foo (1421705502.5811)hello foo (1421705503.5810)请注意,此示例包括CPU在每段时间进行3秒钟的其他操作的模拟。如果你每次都把它改为随机的,那就无所谓了。中的最大值yield线起保护作用sleep如果调用函数的时间比指定的时间长,则从负数开始。在这种情况下,它将立即执行,并在下一次执行的时间上弥补所损失的时间。
随时随地看视频慕课网APP

相关分类

Python
我要回答