有没有一种解决方案可以让您在线程中每隔指定的秒数执行一次任务而不会使线程进入睡眠状态?
Is there a solution that allows you to perform a task every specified number of seconds in a thread without putting it to sleep?
就像在提问中是否有一种解决方案可以让您在线程中每隔指定的秒数执行一次任务,而无需使其在 python 中休眠?
第一种方式
您可以使用 threading.Timer
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
第二种方式
检查具体时间是否已过。然后运行your_function()
在一个线程
import time
current_milli_time = lambda: int(round(time.time() * 1000))
def your_function():
last_run_millis = current_milli_time()
while 1:
now_millis = current_milli_time()
delta_time = now_millis - last_run_millis
if delta_time > 3000:
last_run_millis = now_millis
print("Do your stuff here")
your_function()
以下代码每 30 秒运行一次线程 1:
import threading
def thread1:
pass
L1.acquire()
if "__name__" == "__main__":
specific_time = 30
t1 = threading.Thread(target=thread1)
L1 = threading.Lock(blocking=True)
t1.start()
init_time = time.time()
while 1:
if (time.time() - init_time) >= specific_time:
L1.release()
init_time = time.time()
就像在提问中是否有一种解决方案可以让您在线程中每隔指定的秒数执行一次任务,而无需使其在 python 中休眠?
第一种方式
您可以使用 threading.Timer
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
第二种方式
检查具体时间是否已过。然后运行your_function()
在一个线程
import time
current_milli_time = lambda: int(round(time.time() * 1000))
def your_function():
last_run_millis = current_milli_time()
while 1:
now_millis = current_milli_time()
delta_time = now_millis - last_run_millis
if delta_time > 3000:
last_run_millis = now_millis
print("Do your stuff here")
your_function()
以下代码每 30 秒运行一次线程 1:
import threading
def thread1:
pass
L1.acquire()
if "__name__" == "__main__":
specific_time = 30
t1 = threading.Thread(target=thread1)
L1 = threading.Lock(blocking=True)
t1.start()
init_time = time.time()
while 1:
if (time.time() - init_time) >= specific_time:
L1.release()
init_time = time.time()