为什么time.sleep在threading.Thread中不能按预期工作

2024-06-10 09:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: trueformatmessagedatetimetimesleepnowlast