setTimeout in Python

November 14, 2014

Today in a threaded Python project I work on, I had to delay the execution of a function for a bit, much like the ubiquitous setTimeout() in JavaScript.

Of course, sleep(3) is an option, but it will halt all execution completely while waiting. Instead, a Timer object is exactly what you want.

However, wrapping the code in question inline makes the application code much harder to read, so I wrote a decorator instead:

# utils.py

import threading
from functools import wraps

def delay(delay=0.):
    """
    Decorator delaying the execution of a function for a while.
    """
    def wrap(f):
        @wraps(f)
        def delayed(*args, **kwargs):
            timer = threading.Timer(delay, f, args=args, kwargs=kwargs)
            timer.start()
        return delayed
    return wrap

How do you use it?

#main.py

from utils import delay

@delay(3.0)
def my_func(arg1, arg2):
    print arg1, arg2

if __name__ == '__main__':
    my_func('Hello', 'world')

My future self will find this blog post very helpful when the problem comes up next, I hope so will you.

Was this helpful? Buy me a coffee with Bitcoin! (What is this?)

Updating Adobe Flash Without Restarting Firefox

No reason for a Flash upgrade to shut down your entire browser, even if it claims so.It's 2015, and the love-hate relationship of the Web...… Continue reading

Reddit's Fail-Alien (or "Fail-ien?")

Published on January 15, 2015