Implementing a Custom SetInterval in Python

When working with Python, particularly in applications involving timed or repeated execution of functions, the built-in options can sometimes feel a bit limiting. To enhance flexibility and control, I’ve crafted a SetInterval class, modeled after JavaScript’s setInterval method but adapted for Python’s threading model. This post will explore this utility class, diving into its structure and use cases.

The Class Explained

The purpose of this is to repeatedly execute a function at specified intervals. This is achieved using Python’s threading.Timer class, which is part of the standard library. Here’s a breakdown of the class components:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from threading import Timer

class SetInterval:
"""
A class that mimics the JavaScript setInterval method for Python, using threading.

Attributes:
func (Callable): The function to be executed repeatedly.
sec (float): Time interval between function executions.
args (list, optional): Positional arguments for the function.
kwargs (dict, optional): Keyword arguments for the function.
"""
def __init__(self, func, sec, run_now=False, args=None, kwargs=None):
self.func = func
self.sec = sec
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self.thread = None
self.start(run_now)

def start(self, run_now=False):
"""
Starts or restarts the timer for function execution.

Args:
run_now (bool): If True, the function is executed immediately before starting the timer.
"""
def func_wrapper():
self.func(*self.args, **self.kwargs)
self.start()

if run_now:
self.func(*self.args, **self.kwargs)

self.thread = Timer(self.sec, func_wrapper)
self.thread.start()

def cancel(self):
"""
Stops the timer, effectively ending repeated function execution.
"""
if self.thread is not None:
self.thread.cancel()
self.thread = None

Usage

To use the SetInterval class, simply instantiate it with the function you wish to execute and the interval at which you want it to run:

1
2
3
4
5
6
7
8
9
10
11
12
def my_function(message, severity='INFO'):
print(f"[{severity}] {message}")

# Create an instance of SetInterval to run 'my_function' every 5 seconds
timer = SetInterval(my_function,
5,
args=['Hello, world!'],
kwargs={'severity': 'DEBUG'},
run_now=True)
# Output: [DEBUG] Hello, world!
# To cancel the interval
timer.cancel()

Advantages and Considerations

This implementation offers a robust way to handle periodic function execution in Python. It’s particularly useful in scenarios where you need a simple, lightweight timer that doesn’t block the main thread. However, it’s important to note that this approach uses threading, which may not be ideal for CPU-bound tasks due to Python’s Global Interpreter Lock (GIL). For I/O-bound tasks, it should perform well.

Conclusion

The SetInterval class provides a Pythonic way to mimic JavaScript’s setInterval functionality, offering an easy-to-use interface for periodic function execution within your applications. Whether you’re developing GUIs, working on a server-side script, or simply need to run periodic checks in your code, this class can be a handy addition to your toolkit.

I hope you find this implementation useful for your projects! Feel free to modify and adapt the code to fit your needs more closely. The GitHub-Gist for this code can be found here. Happy coding!