Public
Authored by ThatIsAPseudo

Python asynchronous timers

This is a short snippet to ease the use of asynchronous timers in Python, based on the time() function.

Have a look :

import time

class AsyncProcess:
    def __init__(self):
        self.timers = {}

    def wait(self, func, delay, args):
        if func.__name__ not in self.timers:
            self.timers[func.__name__] = time()
        elif time() - self.timers[func.__name__] > delay:
            self.timers[func.__name__] = time()
            return func(*args)

def task1():
    print('Task 1') # Here is the tasks 1's code
    return 1 # You can also use the return statement

def task2(a, b):
    print('Task 2 : ', a + b)

ap = AsyncProcess()

while True:
    result1 = ap.wait(task1, 1)
    ap.wait(task2, 2, (2,3)) # You can pass arguments to the function
Edited
snippet.py 374 Bytes
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment