在Python中,使用多线程来控制任务的运行时间可以通过以下几种方法实现:
1. 使用`threading.Timer`类:
import threading
import time
def task():
print("Task executed")
重新设置定时器
threading.Timer(5, task).start()
启动定时任务
timer = threading.Timer(5, task)
timer.start()
主线程执行其他任务
while True:
pass
2. 使用`threading.Thread`和`time.sleep`:
import threading
import time
class TimerThread(threading.Thread):
def run(self):
while True:
time.sleep(60) 等待60秒
执行任务
print("Task executed")
创建并启动定时线程
timer = TimerThread()
timer.start()
主线程执行其他任务
while True:
pass
3. 使用`concurrent.futures.ThreadPoolExecutor`(推荐,适用于Python 3.2及以上版本):
import concurrent.futures
import time
def task():
print("Task executed")
重新设置定时器
concurrent.futures.ThreadPoolExecutor(max_workers=1).submit(task)
启动定时任务
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
executor.submit(task)
主线程执行其他任务
while True:
pass