import threading, time
from datetime import datetime, timedelta
import whatap.util.logging_util as logging_util
def async( callback, *args, **kwargs ):
    t = threading.Thread(target=callback, args=args, kwargs=kwargs )
    t.setDaemon(True)
    t.start()

    return t

def asyncLoop( callback, interval,  *args, **kwargs ):
    def __infinite_run():
        lastExecuted = None
        while True:
            now = datetime.now()
            if not lastExecuted or now - lastExecuted > timedelta(seconds=interval):
                try:
                    lastExecuted = now
                    callback(*args, **kwargs)
                except Exception, e:
                    logging_util.debugStack(e)
            time.sleep(1)

    t = threading.Thread(target=__infinite_run, args=args, kwargs=kwargs )
    t.setDaemon(True)
    t.start()

    return t


def cpuOverloadProtect(i, interval, sleepTime = 0.05):
    if i > 0 and i % interval==0:
        time.sleep(sleepTime)


