Jazziwicz
Jazziwicz

Reputation: 53

Scheduling task to run every n seconds, starting at a specific time

When using the schedule package in Python, I would like to schedule a task to start at a specific time, and then run every 10 seconds. I was able to get the task to run every 10 seconds, using schedule.every(10).seconds.do(x) and I also got it to run at a set time, using schedule.every().day.at('13:25').do(x). But how would I put these together? I tried to combine them into the following, but I got RecursionError: maximum recursion depth exceeded

import schedule
import time


def test():
    print('Hello, World!')

def sched_job():
    schedule.every(10).seconds.do(test)

    while True:
        schedule.run_pending()
        time.sleep(1)

schedule.every().day.at('13:56').do(sched_job)

while True:
    schedule.run_pending()
    time.sleep(1)

sched_job()

Upvotes: 2

Views: 19218

Answers (1)

acidtobi
acidtobi

Reputation: 1365

Don't call run_pending() from inside your job, just schedule an additional job and use your main loop to call it. The only thing you need to change in your code is removing the while True block in sched_job(). Also, in order to prevent a second schedule to be created every 10 seconds on the next day at the given time, the outer job should immediately cancel itself once it is executed once. You can do this by returning schedule.CancelJob.

Here is the modified code:

import schedule
import time 

def test():
    print('Hello, World!')

def sched_job():
    schedule.every(10).seconds.do(test)
    return schedule.CancelJob

schedule.every().day.at('13:56').do(sched_job)

while True:
    schedule.run_pending()
    time.sleep(1)

Upvotes: 3

Related Questions