Problem of the Day
A new programming or logic puzzle every Mon-Fri

Cron Job

Today's goal is to create a cron job type function for your favorite programming language (or reimplement one). The function should be able to take in an integer (seconds) and run a function every N seconds. For bonus provide a way to run the function every N Minutes, Hours, or Days.

Permalink: http://problemotd.com/problem/cron-job/

Comments:

  • Johnathan - 10 years, 4 months ago

    import time
    
    def cronjobtypefunction(seconds):
        start = time.clock()
    
        while seconds > time.clock() - start:
            print time.clock()
    
    q = raw_input('How do you want the cron job type function to run? Enter s for seconds or m for minutes: ')
    if q == 'm' or q == 'M':
        t = float(raw_input('How many minutes do you want to run the cron job type function?'))
        t = t * 60
    elif q == 's' or q == 'S':
        t = float(raw_input('How many seconds do you want to run the cron job type function?'))
    
    cronjobtypefunction(t)
    

    reply permalink

  • Johnathan - 10 years, 4 months ago

    Oops...forgot to do hours and days. Oh well, I made my submission. Guess I lose out on bonus.

    reply permalink

  • David - 10 years, 4 months ago

    Why not use time.sleep() ? Your while loop is actively counting instead of suspending the execution thread.

    reply permalink

  • Johnathan - 10 years, 4 months ago

    I guess I misunderstood the concept.

    reply permalink

  • David - 10 years, 4 months ago

    S'all good. This website is (potentially) a great place to learn this kind of stuff, so long as other commenters actually say something. Lots of this code will end up being quick and dirty, but that can be a good way to catch some of one's ingrained habits.

    reply permalink

  • Johnathan - 10 years, 4 months ago

    100% honest I love feedback. If you want to take the time to read over my stuff and give suggestions I would really like it.

    Don't want you to think I'm taking it the wrong way. I know some things, but in the big picture I'm still fairly new.

    reply permalink

  • David - 10 years, 4 months ago

    I added a randomized exit condition so it does not require a forced quit.

    import time
    import random
    
    def checkOnExitCondition():
        print "This is where one could check for some kind of exit logic"
        retVal = random.uniform(0,1) < 0.25
        return retVal
    
    def cronJob():
        print "This print is a placeholder for a real cron job"
    
    def cronFunc(sec, mins = 0, hr = 0, day = 0):
        exitCondition = 0
        timetosleep = 60*(60*(24*day + hr) + mins) + sec
        while(not exitCondition):
            time.sleep(timetosleep)
            cronJob()
            exitCondition = checkOnExitCondition()
    
    print "Start:"
    cronFunc(1)
    print "Good thing it randomly finished"
    

    reply permalink

  • Nick Krichevsky - 10 years, 4 months ago

    I decided to do it two ways because I am not sure which would be better from a system standpooint.

    Solution 1, time.sleep()

    from time import sleep
    def function():
        print "I'm running!"
    print "Enter how long until this function runs. Days,Hours,Mins,Seconds"
    q = raw_input()
    times = q.split(',')
    seconds = 0
    div = 86400
    for item,i in zip(times,range(len(times))):
        seconds+=int(item)*div
        if i==0:
            div/=24
        else:
            div/=60
    while True:
        sleep(seconds)
        function()
    

    Solution 2, Custom timer

    from threading import Event,_Timer
    class CronTimer(_Timer):
        def __init__(self,interval,function,*args,**kwargs):
            _Timer.__init__(self,interval,function,args,kwargs)
            self.interval = interval
            self.function = function
            self.args = args
            self.kwargs = kwargs
            self.finished = Event()
        def run(self):
            while True:
                super(CronTimer,self).run()
                self.finished = Event()
    
                print 'hm'
    def function():
        print "I'm running!"
    
    print "Enter how long until this function runs. Days,Hours,Mins,Seconds"
    q = raw_input()
    times = q.split(',')
    seconds = 0
    div = 86400
    for item,i in zip(times,range(len(times))):
        seconds+=int(item)*div
        if i==0:
            div/=24
        else:
            div/=60
    
    c = CronTimer(seconds,function)
    c.start()
    

    reply permalink

Content curated by @MaxBurstein