import time



class CheapCronJob(object):

    """

    Object representing a cron job. Keeps track of when it was last run.

    """

    def __init__(self, callback, interval=86400):

        self.interval = interval

        self.callback = callback

        self.lastcall = time.time()

       

    def check(self, now=None):

        """

        Check if this job should be run or not. Usually this method is called by

        the job's manager. Now should never be given unless a batch of cronjobs

        are checked (eg by a manager).

        """

        now = now or time.time()

        if now - self.lastcall > self.interval:

            self.lastcall += self.interval # don't make the deviation worse.

            self.callback()

           

class CheapCronManager(object):

    """

    Mana

    """

    def __init__(self):

        self.crons = set()

       

    def daily(self, callback):

        """

        Shortcut function to register a cron to run daily.

        """

        self.register(callback)

        return callback

       

    def weekly(self, callback):

        """

        Shortcut function to register a cron to run weekly.

        """

        self.register(callback, 604800)

        return callback

       

    def hourly(self, callback):

        """

        Shortcut function to register a cron to run hourly.

        """

        self.register(callback, 3600)

        return callback

       

    def register(self, callback=None, interval=86400):

        """

        Register a callback to be run every 'interval' seconds.

        """

        if callback is None:

            def deco(func):

                self.register(func, interval)

                return func

            return deco

        self.crons.add(CheapCronJob(callback, interval))

        return callback

       

    def check(self):

        """

        Check all cronjobs registered to this manager.

        """

        # For a minimal performance gain, we only get time.time() once.

        now = time.time()

        for cron in self.crons:

            cron.check(now)