Python如何为Threading Timer自定义终止前执行的函数?
问题解答:Timer超时回调中添加自定义操作
你直接写Timer(2900, custom_function(recover))会导致**custom_function被立即执行**,而不是等待2900秒后触发——因为Timer的第二个参数需要传入一个可调用对象(比如函数名),而你这样写是直接调用了函数,把返回值传给了Timer,自然达不到预期效果。
两种正确实现方式
1. 使用lambda表达式包裹
通过lambda把带参数的函数调用包装成无参的可调用对象:
timer = Timer(2900, lambda: custom_function(recover))
2. 使用functools.partial(更清晰,适合复杂场景)
导入functools.partial,它可以帮你绑定函数参数,生成新的可调用对象:
from functools import partial timer = Timer(2900, partial(custom_function, recover))
完整代码示例(含超时记录)
先定义你的自定义函数,实现日志记录+进程终止:
import subprocess import shlex from threading import Timer from functools import partial import datetime def custom_function(process): # 自定义操作:记录超时信息(可写入日志文件或控制台) log_content = f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 进程PID {process.pid} 运行超时,执行命令: {' '.join(process.args)}" print(log_content) # 写入日志文件 with open("timeout_logs.txt", "a", encoding="utf-8") as f: f.write(log_content + "\n") # 执行进程终止 process.kill() # 假设q(队列)和my_env(环境变量)已提前定义 while not q.empty(): try: cmd = "itf -obj " + q.get() recover = subprocess.Popen(shlex.split(cmd), env=my_env, shell=False) # 用partial绑定回调参数 timer = Timer(2900, partial(custom_function, recover)) try: timer.start() # communicate()已会阻塞等待进程结束,无需额外调用wait() recover.communicate() q.task_done() finally: print("进程在超时前完成") timer.cancel() except Exception as e: print(f"执行出错: {str(e)}") q.task_done() continue
补充说明
recover.communicate()本身会阻塞直到进程结束,后续的recover.wait()可以省略,避免重复等待- 日志记录部分可根据需求调整,比如使用Python标准库
logging来管理日志级别和输出格式
内容的提问来源于stack exchange,提问作者Rankinstudio
相关产品推荐
相关产品推荐

