Python超时计数器?

时间:2017-06-20 13:18:57

标签: python multiprocessing

我在python中有一个程序,它将监听输入信号。但这可能需要很长时间才能等待,所以我希望每隔5秒显示一条消息,说“还在等待”

但是我不希望计数器功能中的延迟1秒停止程序监听信号,因为信号是定时的,不正确的时序会产生不正确的结果。

我到目前为止已经达到了这一点,但每次$ temp_2增加时整个脚本都会延迟1秒

#If option number 1 was selected, proceed
if(int(input_string) == 1):
    input_string = ""
    temp_2 = 0
    print('Currently listening for messages. System still working. Please wait.')

        while True:
            if(input_0 == False):
                input_string = input_string + "0"
                temp_1 = temp_1 + "0"

            if(input_1 == False):
                input_string = input_string + "1"
                temp_1 = temp_1 + "1"

            if(len(input_string) ==  8):
                output_string = output_string + chr(int(input_string, 2))
                input_string = ""

                if(len(temp_1) == 40):
                    if(temp_1 == "0011110001100101011011100110010000111110"):
                        print('Received terminator!')
                    else:
                        temp_1 = temp_1[8::]

                #increase the counter, but don't stop the script from
                #listening for the input. can it be done? 
                temp_2 = timeout_counter(temp_2)

                print(temp_2)

                if(temp_2 == 5):
                    print('still working. not broken.')
                    temp_2 = 0

以下是我的timeout_counter()函数:

def timeout_counter(temp_2):
    temp_2 = temp_2 + 1
    time.sleep(1)
    return (temp_2)

1 个答案:

答案 0 :(得分:1)

使用time.time(),而不是使用time.sleep,你可以只使用time.time()来处理给定迭代的时间戳和前一个时间戳的时间戳。

您的算法应如下所示:

#If option number 1 was selected, proceed
if(int(input_string) == 1):
    input_string = ""
    temp_2 = time.time()
    print('Currently listening for messages. System still working. Please wait.')

        while True:
            if(input_0 == False):
                input_string = input_string + "0"
                temp_1 = temp_1 + "0"

            if(input_1 == False):
                input_string = input_string + "1"
                temp_1 = temp_1 + "1"

            if(len(input_string) ==  8):
                output_string = output_string + chr(int(input_string, 2))
                input_string = ""

                if(len(temp_1) == 40):
                    if(temp_1 == "0011110001100101011011100110010000111110"):
                        print('Received terminator!')
                    else:
                        temp_1 = temp_1[8::]

                #increase the counter, but don't stop the script from
                #listening for the input. can it be done? 
                temp_2 = timeout_counter(temp_2)

                print(temp_2)

                if(time.time() - temp_2 >= 5.):
                    print('still working. not broken.')
                    temp_2 = time.time()

你的timeout_counter()函数现在没用了:)