I need help please, I use schedule.every().day.at("17:40").do(my_function) and I would like my program to run normally and when the schedule.every().day.at("17:40").do(my_function) arrives, it executes the associated function but then it comes back in my loop and wait for another day etc.... I dont know how to do it because i think schedule.every().day.at("17:40").do(my_function) need while1: schedule.run_pending() time.sleep(1) So i dont know how to changes this 3 lignes to make my programme work. Thanks!
Asked
Active
Viewed 29 times
-1
-
run it in separated thread. – furas Dec 23 '20 at 03:16
-
yes thanks but how i can do that please ? – le_marseillais Dec 23 '20 at 10:53
-
1search information about modules [threading](https://docs.python.org/3/library/threading.html) or [multiprocessing](https://docs.python.org/3/library/multiprocessing.html). There should be many tutorials (even video). And there is many question and answers on Stackoverflow. – furas Dec 23 '20 at 16:02
-
but first you should check [documentation](https://schedule.readthedocs.io/en/stable/) because I found there [How to continuously run the scheduler without blocking the main thread?](https://schedule.readthedocs.io/en/stable/faq.html#how-to-continuously-run-the-scheduler-without-blocking-the-main-thread) - it seams they already put it in thread and you need to run `run_continuously()` – furas Dec 23 '20 at 16:04
1 Answers
0
You would have to run it in separated threading or multiprocessing.
But first you should check documentation because I found in Common Questions
:
How to continuously run the scheduler without blocking the main thread?
They created class Scheduler
which put it in thread and you need to run run_continuously()
But I use it to created shorter example
import schedule
import time
import threading
# --- functions ---
stop_running = threading.Event() # to control loop in thread
def run_continuously(scheduler, interval=1):
#print('starting loop in thread')
while not stop_running.is_set():
schedule.run_pending()
time.sleep(interval)
#print('stoping loop in thread')
def job():
print("I'm working...")
# --- main ---
schedule.every(1).minutes.do(job)
# run schedule in thread
schedule_in_thread = threading.Thread(target=run_continuously, args=(schedule,))
schedule_in_thread.start()
# run other code
#print('starting main loop')
try:
while True:
print("other code")
time.sleep(3)
except KeyboardInterrupt as ex:
print('stoping', ex)
#print('stoping main loop')
# stop schedule in thread
stop_running.set() # to stop loop in `run_continuously`
schedule_in_thread.join() # wait until thread finish
I use try/except
with KeyboardInterrupt
only to gracefully stop program when I press Ctrl+C - and code may stop thread.
furas
- 95,376
- 7
- 74
- 111