首页 > 解决方案 > 定期调度功能期间的递归错误

问题描述

我正在为我需要编写的函数运行一些测试,其中我有两个单独的定时函数在每次执行的可变时间内发生。这些功能必须是非阻塞的。

我创建的测试如下:

import sched, time
import threading

s = sched.scheduler(time.time, time.sleep)
s2 = sched.scheduler(time.time, time.sleep)

def do_something(sc):
    print("doing stuff.")
    sc.enter(5, 1, do_something, (sc,))
    sc.run()

def do_something_else(sc):
    print("doing other stuff.")
    sc.enter(3, 1, do_something_else, (sc,))
    sc.run()

x = threading.Thread(target=do_something, args=(s,), daemon=True)
x.start()
y = threading.Thread(target=do_something_else, args=(s,), daemon=True)
y.start()


while 1:
    pass

该测试产生了我正在寻找的结果。在每个方法的每次调用中,我都可以更新下一个函数调用的延迟量。

我计划使用它的程序将使用这种方法并使循环一次运行长达数小时。我已经让这段代码运行了一段时间,看看它是否能够做到这一点。大约 10-15 分钟我遇到了这个异常:

RecursionError: maximum recursion depth exceeded while calling a Python object

我是 python 新手,来自 JS 和 Java,但这个错误是否类似于 stackoverflow?此错误是否会阻止我使用所有内存并使应用程序崩溃?我看到使用系统模块可以改变深度。

据我了解,我创建的 sched 应该在下一个 sched 启动后终止并销毁,这意味着内存不能堆积?如果我更改了递归限制,它是否允许我在所需的时间内运行我的程序而不会出现内存崩溃?或者这个错误是否直接暗示我正在走向内存崩溃?

标签: pythonmultithreadingrecursionscheduled-tasks

解决方案


Python 设置了 1000 次迭代的标准递归限制。但是您可以使用sys库对其进行修改。您可以使用 来检查递归限制sys.getrecursionlimit() ,并且可以使用 来更改递归限制sys.setrecursionlimit()

例如,如果要将递归限制更改为 2000,则可以运行sys.setrecursionlimit(2000).

但是,如果您将递归限制设置得太高,并且您的代码不断迭代,您可能会得到 amemory error并且您的程序会崩溃。


推荐阅读