如何给线程添加定时

问题描述

在线程运行中如何添加定时

问题原因

解决方案

使用 Python 的 schedule 模块来实现定时任务的功能,并在每隔n分钟执行一次函数。

示例代码:

import schedule
import time
import threading

# 定义需要定时执行的任务
def func(num):
time.sleep(10)
thread_name = threading.current_thread().name
data = str(num) + "当前线程:" + thread_name + '\n'
print(data)
file_path = r"c:\users\admin\Desktop\test\modify\test.txt"
with open(file_path, 'a', encoding='utf-8') as f:
f.write(data)

# 设置定时任务,每隔一分钟执行一次 func 函数
schedule.every(1).minutes.do(func, num=123)

# 持续运行,直到手动结束
while True:
schedule.run_pending()
time.sleep(1)