H
H
hagnoherze2021-09-19 06:53:31
Python
hagnoherze, 2021-09-19 06:53:31

Stop flow. Stop a task?

When the button is clicked, the code is executed.

def job1():
    print("Work job1")
def job2():
    print("Work job2")

def run():
    schedule.every(1).minutes.do(job1)
    schedule.every(10).seconds.do(job2)
 
    while True: 
        schedule.run_pending() 
        time.sleep(1)
 
thread = Thread(target=run)
thread.start()

We need to add a button that stops the output of job2.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SaShATeR, 2021-09-19
@hagnoherze

You can stop the loop with the break command: specify the condition under which you want to stop the output of job2 and break the loop.
while True:
schedule.run_pending()
time.sleep(1)
if loop termination condition:
break
But in this case, the output of both job2 and job1 will stop. If you want to stop outputting only job2, then you create two modules: one for job1, the other for job2.
def run1():
schedule.every(1).minutes.do(job1)
while True:
schedule.run_pending()
time.sleep(1)
def run2():
schedule.every(10).seconds.do(job2)
while True:
schedule.run_pending()
time.sleep(1)
if loop break condition:
break

V
Vindicar, 2021-09-19
@Vindicar

Use threading.Event.

import threading

def run(stop: threading.Event):
  while not stop.wait(timeout=1.0): # ожидание и проверка сигнала о завершении
    schedule.run_pending()

stop_event = threading.Event()
worker = threading.Thread(target=run, args=(stop_event,))
worker.start()
#когда надо остановить поток worker
stop_event.set()

The beauty of this approach is that the loop will break immediately on the stop_event signal, and not when the next wait ends. You can also force multiple threads to use the same Event object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question