Python计时以触发特定事件 [英] Python timing in order to trigger specific events

查看:242
本文介绍了Python计时以触发特定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我想运行一个调用默认动作的函数,持续20秒.但是,在这20秒内有5个特定的时间触发其他功能.为了简化代码,我用简单的打印命令替换了动作"功能.

In Python I would like to run a function calling a default action for 20 seconds. However, there are 5 specific timings within these 20 seconds when another function should be triggered. In order to simplify my code, I have replaced the "action" functions with simple printing commands.

这是我到目前为止的内容-输出似乎还可以,它持续10秒钟,并打印时间和默认状态/动作.但是触发的动作丢失了!有没有更好/正确的方法可以做到这一点?

Here is what I have so far - The output seems ok, in that it lasts for 10 seconds and prints the time and the default state/action. But the triggered action is missing! Is there a better/correct way to do this?

import random
import time
import numpy as np
import itertools

def uniform_min_range(a, b, n, min_dist):
    while True:
        atimes = np.random.uniform(a, b, size=n)
        np.sort(atimes)
        if np.all(np.diff(atimes) >= min_dist):
            return atimes

def timings():
    global times
    times = uniform_min_range(0, 20, 5, 1.0) 
    print 'beep times: ', times

def defaultAction():
    global start
    print 'wobble'

def triggeredAction():
    global start
    print 'actionnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'

def main():
    global times
    timings()
    print 'beep times: ', times
    start = time.time()
    t_end = time.time() + 20   #### end after 20 seconds
    while time.time() < t_end: #### for 20 sec/ until end reached
        print str(time.time()-start)
        if (time.time()-start) == times[0] or (time.time()-start) == times[1] or (time.time()-start) == times[2] or (time.time()-start) == times[3]:
            triggeredAction()
        elif (time.time()-start) != times[0] or (time.time()-start) != times[1] or (time.time()-start) != times[2] or (time.time()-start) != times[3]:
            defaultAction()

    print "END"

main()

推荐答案

time.time() 返回自纪元以来的第二个浮点数,例如:

time.time() returns second since epoch as a floating point number like:

>>> import time
>>> time.time()
1465572505.891256

如果您的比较:

time.time()-start) == times[0]

time.time()的时间不能精确到微秒(这取决于系统),因此==不会为True,并且您将永远无法获得triggeredAction().

to time.time() isn't correct down to the microsecond (this depends on the system), then the == won't be True and you'll never get your triggeredAction().

如果适合您,请在第二秒之前执行操作,请使用: int(time.time()),并对uniform_min_range返回值执行相同的操作-假设每秒分辨率对您来说还可以.否则,您需要为触发的动作检查引入一个范围(+或-1s).

Do things by the second if that works for you, use: int(time.time()) and do the same for your uniform_min_range return values - assuming per second resolution is ok for you. Otherwise you'll need to introduce a range (+ or - 1s) to your triggered action check.

这篇关于Python计时以触发特定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆