簡體   English   中英

在一定時間后使用 time.sleep() 打印值

[英]Print values using time.sleep() after certain time

我有一個使用time.sleep()的程序我正在運行一些操作,每個操作都在指定的時間間隔后完成。 但是, time.sleep() 打亂了這個間隔。 有沒有辦法讓它們中的每一個都以指定的時間間隔同時運行,但不會中斷時間。 代碼:

import time
def a():
    print("10 seconds have passed since execution")
def b(): 
    print("20 seconds have passed since execution")
def c():
    print("5 seconds have passed since execution")

def runA():
    time.sleep(10)
    a()

def runB():
    time.sleep(20)
    b()

def runC():
    time.sleep(5)
    c()

while True:
    runA()
    runB()
    runC()

現在,在執行程序后,我希望程序在 5 秒后打印c() ,在 10 秒后打印 a( a() ,在 20 秒后打印b() 但是程序打印a()等待 20 秒打印b()並等待 5 秒並打印c() 任何不涉及更改程序睡眠時間的簡單方法對於該程序是可能的嗎?

您必須使用threading / multiprocessing / concurrency來同時運行功能。

threading的最小示例。

target=中,您必須使用不帶()的函數名稱,稍后的thread將使用()來啟動此 function。

import time
import threading

def a():
    print("10 seconds have passed since execution")
    
def b(): 
    print("20 seconds have passed since execution")
    
def c():
    print("5 seconds have passed since execution")

def runA():
    time.sleep(10)
    a()

def runB():
    time.sleep(20)
    b()

def runC():
    time.sleep(5)
    c()

while True:
    print('start')
    
    # create threads    
    t1 = threading.Thread(target=runA) # function's name without ()
    t2 = threading.Thread(target=runB) # function's name without ()
    t3 = threading.Thread(target=runC) # function's name without ()

    # start code in threads    
    t1.start()
    t2.start()
    t3.start()
    
    # wait for ends
    t1.join()
    t2.join()
    t3.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM