为什么time.sleep在threading.Thread中无法按预期工作

时间:2018-10-18 14:18:11

标签: python python-3.x

Python 3.5.1

flush_worker函数旨在生成间隔60秒的刷新信号。但是,输出显示time.sleep的唤醒时间少于1秒。

问题1>为什么显示的第一条sleep now消息没有相应的wake up message

问题2>为什么time.sleep函数每两个周期只能工作一次?

谢谢

def flush_worker():
    global g_flush_now
    last_flush_t = datetime.datetime.now()

    while True:
        now = datetime.datetime.now()
        time_diff = (now - last_flush_t).seconds
        if time_diff >= 60:
            last_flush_t = now
            print("flush_worker: flush {0}".format(now))
            sys.stdout.flush()
            g_flush_now = True

        now_a = datetime.datetime.now()
        print("[{0}] sleep now".format(now_a))
        sys.stdout.flush()
        time.sleep(60)
        now_b = datetime.datetime.now()
        print("[{0}] wake up".format(now_b))
        sys.stdout.flush()

def main()        
    flush_timer = threading.Thread(target=flush_worker, daemon=True)
    flush_timer.start()

    other_function()


Output:

[2018-10-18 09:08:32.962835] sleep now                              >> why this sleep message doesn't immediately follow the wake up message?
[2018-10-18 09:08:33.824594] sleep now
[2018-10-18 09:09:32.980338] wake up                                >>> ~60 seconds gap
flush_worker: flush 2018-10-18 09:09:32.980641
[2018-10-18 09:09:32.980921] sleep now
[2018-10-18 09:09:33.830594] wake up                                >>> ~1 second gap
flush_worker: flush 2018-10-18 09:09:33.830937
[2018-10-18 09:09:33.831261] sleep now                              
[2018-10-18 09:10:33.000973] wake up                                >>> ~60 seconds gap
flush_worker: flush 2018-10-18 09:10:33.001416
[2018-10-18 09:10:33.001831] sleep now                                    
[2018-10-18 09:10:33.870503] wake up                                >>> ~1 second gap
flush_worker: flush 2018-10-18 09:10:33.870570
[2018-10-18 09:10:33.870603] sleep now

0 个答案:

没有答案