Skip to content Skip to sidebar Skip to footer

Can I Set A Threading Timer With Clock Time To Sync With Cron Job In Python

I have a cron job that runs at 12, 12:30,1, 1:30. So every half hour intervals on the clock. I want to run a thread in my python code whenever the cron job runs. I have seen examp

Solution 1:

Almost everything is possible, the real question is why do you want to do this? Keep in mind that cron scheduler won't necessarily execute jobs at precise times and furthermore, checking the time in Python won't necessarily correspond to cron's time, so if you need to execute something in your Python code after a cron job is executed, you cannot rely on measuring timings in Python - you actually need to 'communicate' from your cron job to your Python script (the easiest would be using datagram sockets)

But, if you want to simulate cron scheduler in Python, one way to do it is to use the datetime module to get the current time and then calculate the amount of time.sleep() you need before your command fires again, e.g.:

def schedule_hourly_task(task, minute=0):
    # get hourly offset in seconds in range 1-3600
    period = ((60 + minute) % 60) * 60 or 3600
    while True:
        # get current time
        current = datetime.datetime.now()
        # count number of seconds in the current hour
        offset = (current - current.replace(minute=0, second=0, microsecond=0)).total_seconds()
        # calculate number of seconds til next period
        sleep = period - offset % period
        if offset + sleep > 3600:  # ensure sleep times apply to full hours only
            sleep += 3600 % period
        # sleep until the next period
        time.sleep(sleep)
        # run the task, break the loop and exit the scheduler if `False` is returned
        if not task():
            return

Then you can use use it to run whatever task you want at any full_hour + minute offset. For example:

counter = 0
def your_task():
    global counter
    counter += 1
    if counter > 2:
        return False
    return True

schedule_hourly_task(your_task, 15)

And it will execute your_task() function every 15 minutes until your_task() returns False - in this case at hh:15, hh:30 and hh:45 before exiting. In your case, calling schedule_hourly_task(your_task, 30) will call the your_task() function every full 30 minutes for as long as your_task() returns True.


Post a Comment for "Can I Set A Threading Timer With Clock Time To Sync With Cron Job In Python"