dbader / schedule

Python job scheduling for humans.
https://schedule.readthedocs.io/
MIT License
11.62k stars 954 forks source link

How do I pass changing arguments to the jobs thread? #591

Closed bsauvage1 closed 1 year ago

bsauvage1 commented 1 year ago

I have a thread containing all my jobs, and I need to pass an "active" argument that can change overtime. "active" is defined as a global variable and its value correctly changes when I need it, however the schedule doesn't reflect the change in the value. Is there a way to achieve this, short of killing the thread and rebuilding it on argument change (which could cause some issues with the delay introduced in killing/restarting).

In the simplest form, I could do with something that pauses/restarts the scheduler inside the thread when active changes.

Minimal example:

import schedule
import threading

active = True # the value of active changes periodically - controlled by another thread

schedule.every().hour.at(":19").do(run_threaded, read_position(active))
schedule.every().hour.at(":20").do(generate_portfolio, active=active)

def run_threaded(
    job_func,
):
    # job_thread = threading.Thread(target=job_func, args=(active, ))
    job_thread = threading.Thread(target=job_func)
    job_thread.start()

def strategies_task():
    while 1:
        schedule.run_pending()
        time.sleep(1)

p1 = threading.Thread(target=strategies_task, args=(), kwargs={})
p1.start()
bsauvage1 commented 1 year ago

Actually I solved the problem by creating a persistent class to hold these variables, and make the scheduled functions read these from the class.