[英]Run a function at a random time in Python
只要程序正在運行,我希望能夠在隨機時間運行 function。
假設我有這個 function:
def sample_func:
print("Function is running.")
和其他一些正在運行的代碼。 只要程序正在運行,我希望這個 function 在運行其他代碼時隨機運行 5 到 10 分鍾。 這可能嗎?
這是您正在查找的代碼。 將睡眠定時器設置為 5-10 分鍾。 在“主要流程”function 中插入您的主要流程代碼。
import random
import threading
import time
def random_function():
print("Function is running.")
def call_random_function():
while True:
time.sleep(random.randint(1, 5))
random_function()
def main_flow():
"""
Do your main flow here
"""
a = 1
while a < 10:
print(a)
a += 1
time.sleep(10)
if __name__ == '__main__':
threading.Thread(target=call_random_function).start()
main_flow()
print("Program is finished.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.