Python每0.1秒执行函数代码示例

注:这篇文章是Deepseek写的。

如果你不想阻塞其他功能的运行,可以使用 threading 模块来创建一个线程,专门用于定时执行你的函数。这样主程序可以继续运行其他任务,而不会因为 time.sleep() 而被阻塞。

以下是一个使用 threading 的示例代码:

import threading

def my_function():
    print("执行函数")
    # 设置下一次执行
    threading.Timer(0.1, my_function).start()

# 启动定时任务
my_function()

# 主程序可以继续运行其他任务
print("主程序继续运行...")

# 模拟主程序的其他任务
while True:
    print("主程序正在运行...")
    time.sleep(1)  # 这里用 sleep 只是为了演示主程序的其他任务

代码说明:

  1. threading.Timer(0.1, my_function) 会创建一个定时器,在 0.1 秒后执行 my_function

  2. my_function 中,再次调用 threading.Timer,从而实现每 0.1 秒执行一次的效果。

  3. 主程序不会被阻塞,可以继续运行其他任务。

注意事项:

  • 如果你需要停止定时任务,可以通过设置一个标志位来控制定时器的启动和停止。

  • 如果需要更精确的定时控制,可以考虑使用 sched 模块或 asyncio 模块。

例如,使用标志位控制定时任务的停止:

import threading

# 控制定时任务的标志位
running = True

def my_function():
    if running:
        print("执行函数")
        # 设置下一次执行
        threading.Timer(0.1, my_function).start()

# 启动定时任务
my_function()

# 主程序可以继续运行其他任务
print("主程序继续运行...")

# 模拟主程序的其他任务
try:
    while True:
        print("主程序正在运行...")
        time.sleep(1)  # 这里用 sleep 只是为了演示主程序的其他任务
except KeyboardInterrupt:
    # 停止定时任务
    running = False
    print("定时任务已停止")

这样,你可以通过设置 running = False 来停止定时任务。


你遇到的 maximum recursion depth exceeded 错误是因为 threading.Timer 在每次调用 my_function 时都会创建一个新的线程,而 my_function 又会递归地调用自己(通过 threading.Timer),导致递归深度不断增加,最终超出 Python 的默认递归深度限制。

为了避免这个问题,可以使用 threading 模块中的 Event 来控制定时任务的执行,而不是递归地调用 threading.Timer。以下是改进后的代码:

改进方案:使用 threading.Event 和循环

import threading
import time

def my_function():
    print("执行函数")

def timer_loop(stop_event):
    while not stop_event.is_set():
        my_function()
        stop_event.wait(0.1)  # 等待 0.1 秒

# 创建一个事件对象,用于控制定时任务的停止
stop_event = threading.Event()

# 启动定时任务线程
timer_thread = threading.Thread(target=timer_loop, args=(stop_event,))
timer_thread.start()

# 主程序可以继续运行其他任务
print("主程序继续运行...")

# 模拟主程序的其他任务
try:
    while True:
        print("主程序正在运行...")
        time.sleep(1)  # 这里用 sleep 只是为了演示主程序的其他任务
except KeyboardInterrupt:
    # 停止定时任务
    stop_event.set()
    timer_thread.join()
    print("定时任务已停止")

代码说明:

  1. stop_event:这是一个 threading.Event 对象,用于控制定时任务的停止。当 stop_event.set() 被调用时,定时任务会退出循环。

  2. timer_loop:这是一个循环函数,每隔 0.1 秒调用一次 my_function,直到 stop_event 被设置。

  3. stop_event.wait(0.1):等待 0.1 秒,同时检查 stop_event 是否被设置。如果被设置,则退出循环。

  4. timer_thread.join():在主程序退出前,等待定时任务线程结束。

优点:

  • 避免了递归调用,不会触发 maximum recursion depth exceeded 错误。

  • 可以精确控制定时任务的启动和停止。

  • 主程序不会被阻塞,可以继续运行其他任务。

注意事项:

  • 如果你需要更精确的定时控制(例如严格每 0.1 秒执行一次),可以考虑使用 time.monotonic() 来计算时间间隔,而不是直接使用 stop_event.wait(0.1)

  • 如果需要更复杂的定时任务调度,可以使用 sched 模块或 asyncio 模块。

希望这段代码能解决你的问题!如果还有其他需求,请随时告诉我。