1# -*- coding: UTF-8 -*-
2
3import time
4from threading import Thread
5from pychess.System import fident
6
7
8def repeat(func, *args, **kwargs):
9    """ Repeats a function in a new thread until it returns False """
10
11    def run():
12        while func(*args, **kwargs):
13            pass
14
15    thread = Thread(target=run, name=fident(func))
16    thread.daemon = True
17    thread.start()
18
19
20def repeat_sleep(func, sleeptime, recur=False):
21    """
22    Runs func in a thread and repeats it approximately each sleeptime [s]
23    until func returns False. Notice that we sleep first, then run. Not the
24    other way around. If repeat_sleep is called with recur=True, each call
25    will be called with the return value of last call as argument. The
26    argument has to be optional, as it wont be used first time, and it has
27    to be non-None.
28    """
29
30    def run():
31        last = time.time()
32        val = None
33        while True:
34            time.sleep(time.time() - last + sleeptime)
35            if not time:
36                # If python has been shutdown while we were sleeping, the
37                # imported modules will be None
38                return
39            last = time.time()
40            if recur and val:
41                val = func(val)
42            else:
43                val = func()
44            if not val:
45                break
46
47    thread = Thread(target=run, name=fident(func))
48    thread.daemon = True
49    thread.start()
50