Search code examples
pythonpython-decorators

Python decorator to schedule the execution of a function


I need to write a Python decorator with a parameter to schedule the execution of a function.

I've tried to write a function that returns the decorator but it didn't work:

import time


def scheduled(duration):
    def decorator(function):
        time.sleep(duration)
        def new_function(*args, **kwargs):
            return function(*args, **kwargs)
        return new_function
    return decorator


@scheduled(1)
def hello():
    print('Hello, world!')


start = time.time()
hello()
print(f'Execution took {round(time.time() - start, 2)}s')

Output

Hello, world!
Execution took 0.0s

I would like the function to execute after 1s, how can I achieve it ?


Solution

  • The line time.sleep(duration) should be inside the inner function, like this:

    def scheduled(duration):
        def decorator(function):
            def new_function(*args, **kwargs):
                time.sleep(duration)
                return function(*args, **kwargs)
            return new_function
        return decorator
    

    Now it should work