Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Schedules jobs too often if multiple threads are present #630

Open
Klimroth opened this issue Aug 1, 2024 · 1 comment
Open

Schedules jobs too often if multiple threads are present #630

Klimroth opened this issue Aug 1, 2024 · 1 comment

Comments

@Klimroth
Copy link

Klimroth commented Aug 1, 2024

If I schedule two jobs and each job should be run in one thread, the following minimal example does not work

`import schedule
import threading
import time
from datetime import datetime

def do_task_1() -> None:
print(f"{datetime.now().isoformat()} - task 1 execution - thread {threading.current_thread().name} \n")

def do_task_2() -> None:
print(f"{datetime.now().isoformat()} - task 2 execution - thread {threading.current_thread().name} \n")

def task_1_sheduler() -> None:
schedule.every(10).seconds.do(do_task_1)
while True:
time.sleep(1)
schedule.run_pending()

def task_2_sheduler() -> None:
schedule.every(14).seconds.do(do_task_2)
while True:
time.sleep(1)
schedule.run_pending()

def start_thread_1() -> None:
t = threading.Thread(target=task_1_sheduler)
t.start()

def start_thread_2() -> None:
t = threading.Thread(target=task_2_sheduler)
t.start()

start_thread_1()
start_thread_2()
`

I would expect it to conduct do_task_2 every 14 seconds on thread 2 and do_task_1 independently every 10 seconds on thread 1, but it mixes things up

image001

What am I doing wrong?

@azhiv
Copy link

azhiv commented Aug 10, 2024

I encountered the same problem - it turned out that the default scheduler is shared among all threads. If you create a dedicated scheduler scheduler = schedule.Scheduler() in each thread and use it there, the output will match what you expect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants