I have a python method which performs some task time to time. I find the easiest way is to write:
class MyClass:
def a(self):
#perform the task
time.sleep(time_to_sleep)
self.a()
But the method is supposed to run for a long time, possibly for months, which means it method could be called recursively up to 10^4 times.
Is there any risk in doing so?
If you indefinitely keep recursing into your function, Sooner or later you will get the following error -
RuntimeError: maximum recursion depth exceeded
A simple example to show this -
>>> def a():
... global i
... i += 1
... a()
Then I ran this function using as -
>>> i = 0
>>> a()
This gave me the above error, and afterwards when I printed the value of i
it was 999. So sooner or later you can get that error.
You can also change this limit , by calling sys.setrecursionlimit()
, though I would not suggest this, as you may end up blowing the stack, before you even reach the limit (An easier way would be to use while loop as given below in the answer) -
import sys
sys.setrecursionlimit(<limit>)
Or you can also get - MemoryError
- If you are storing lots of data in local namespace, since you are never really returning from the recursive calls , the local namespace of the calling functions never get cleared. So you can even end up blowing up your memory, before you even reach the maximum recursion limit.
And easy way of what you are trying to do would be to use while loop, example -
class MyClass:
def a(self):
while True:
#perform the task
time.sleep(time_to_sleep)