Python 有没有一种解决方案可以让您在线程中每隔指定的秒数执行一项任务,而无需将其置于睡眠状态?

Python 有没有一种解决方案可以让您在线程中每隔指定的秒数执行一项任务,而无需将其置于睡眠状态?,python,multithreading,sleep,Python,Multithreading,Sleep,像在questien中一样,有没有一种解决方案允许您在一个线程中每隔指定的秒数执行一项任务,而不必在python中使其休眠?1st way 你可以用它来做 第二条路 只需检查具体时间是否已过。然后在线程中运行函数() import time current_milli_time = lambda: int(round(time.time() * 1000)) def your_function(): last_run_millis = current_milli_time() whi

像在questien中一样,有没有一种解决方案允许您在一个线程中每隔指定的秒数执行一项任务,而不必在python中使其休眠?

1st way 你可以用它来做

第二条路 只需检查具体时间是否已过。然后在线程中运行函数()

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秒运行一次thread1:

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()

请阅读,并采取行动。问题的关键是,建议回答“是/否”的问题通常没有真正的帮助。仅供参考,还可以阅读一下“XY问题”一词。
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()