I used the schedule library to schedule a function every X seconds:
Want I want is to run this function on separate thread. I found this in the documentation on how to Run the scheduler in a separate thread but I didn't understand what he did.
Is there someone who can explain to me how to do that ?
Update:
This what I tried:
def post_to_db_in_new_thread():
schedule.every(15).seconds.do(save_db)
t1 = threading.Thread(target=post_to_db_in_new_thread, args=[])
t1.start()
First, we must create a new instance of the threading. Thread class and specify the function we wish to execute in a new thread via the “target” argument. The function executed in another thread may have arguments in which case they can be specified as a tuple and passed to the “args” argument of the threading.
Execution of multiple threads on a single CPU in some order is called scheduling. The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads.
To start the thread we need to call the start() member function from thread object i.e. th. start() will start a new thread, which will execute the function threadFunc() in parallel to main thread.
You don't really need to update schedule in every task
import threading
import time
import schedule
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(15).seconds.do(run_threaded, save_db)
while 1:
schedule.run_pending()
time.sleep(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With