Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run schedule function in new thread

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()
like image 322
Amine Harbaoui Avatar asked Aug 27 '18 13:08

Amine Harbaoui


People also ask

How do you execute functions in a separate new thread with the module thread?

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.

Can we schedule thread?

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.

Which Python function can be called to run a thread?

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.


1 Answers

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) 
like image 130
Amine Harbaoui Avatar answered Nov 09 '22 07:11

Amine Harbaoui