import threading

# Dependency for the task


# from https://gist.github.com/Depado/7925679
# Function wrapper
# you can annotate an arbitrary function
# as periodical in its own thread
def periodic_task(interval, times=-1):
    def outer_wrap(function):
        def wrap(*args, **kwargs):
            stop = threading.Event()

            def inner_wrap():
                i = 0
                while i != times and not stop.isSet():
                    stop.wait(interval)
                    function(*args, **kwargs)
                    i += 1

            t = threading.Timer(0, inner_wrap)
            t.daemon = True
            t.start()
            return stop
        return wrap
    return outer_wrap
