python时钟与消息触发,Python计时以触发特定事件

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.

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() returns second since epoch as a floating point number like:

>>> import time

>>> time.time()

1465572505.891256

If your comparison:

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

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().

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值