2

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()
Jazziwicz
  • 43
  • 1
  • 1
  • 5
  • Possible duplicate of [Looping at a constant rate with high precision for signal sampling](http://stackoverflow.com/questions/26774186/looping-at-a-constant-rate-with-high-precision-for-signal-sampling) – ivan_pozdeev Apr 15 '17 at 19:00

1 Answers1

3

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)
acidtobi
  • 1,375
  • 9
  • 13
  • 2
    I'm curious as to why everyone seems to use `time.sleep(1)` so that the `schedule.run.pending()` runs every second. Does is need to run this frequently ? – ProgrammerBret Mar 10 '20 at 23:54