退出 sched.scheduler 模块时遇到问题?

Having trouble quitting sched.scheduler module?

我在我的程序中使用 Selenium Webdriver 来尝试自动化一些东西。然后我解析结果页面,并检查页面中的特定元素。如果页面没有特定元素,那么我使用 sched.scheduler 通过让用户单击按钮(在 Tkinter GUI 中)来重新自动执行任务。该按钮运行一个函数,该函数为 sched.scheduler 安排一个任务,并将任务发送到一个函数,我在该函数中从多处理模块创建了一个新进程。

基本上就是这样:

import time
import sched
from multiprocessing import Process

#the function needs to run for the first time, then waits for user input if an error shows up
#if it's the second time around, the worker function runs the scheduler
global first_time_happening
first_time_happening = True
terminate = False
scheduler = sched.scheduler(time.time, time.sleep)


def worker():
    #insert some working process here using selenium webdriver
    print("Worker happened!")
    global first_time_happening
    if first_time_happening:
        first_time_happening = False
    elif not first_time_happening:
        global relay_to_timer
        relay_to_timer = scheduler.enter(5, 2, timer)
        scheduler.run()


def process():
    p = Process(target=worker)
    #p.daemon = True
    p.start()


def timer():
    if not terminate:
        global relay_to_process
        relay_to_process = scheduler.enter(5, 2, process)
        scheduler.run()
    if terminate:
        scheduler.cancel(relay_to_process)
        scheduler.cancel(relay_to_timer)


def quit_button():
    global terminate
    terminate = True
    if scheduler.empty:
        print("The line is empty")
    elif not scheduler.empty:
        print("Something in the queue!")
    while not scheduler.empty:
        scheduler.cancel(relay_to_process)
        scheduler.cancel(relay_to_timer)

worker()

#simulating where the GUI asks a question, person presses a button, and the button redirects them
#to function worker()

worker()

#simulating a user press the quit button
quit_button()

即使在我 "hit" 退出(或在本例中调用退出函数)后,它仍会继续运行。我一直收到队列为空的消息,但我不确定为什么它不起作用?感谢任何帮助,谢谢!!

即使队列为空,调度程序也会保持 运行,以防有人(可能是另一个线程)再次输入内容。我相信让它结束的方法是引发异常(无论是来自动作还是延迟函数)——.run 将传播它并且你可以捕获它。

即...

class AllDoneException(Exception): pass

def worker():
    #insert some working process here using selenium webdriver
    print("Worker happened!")
    global first_time_happening
    if first_time_happening:
        first_time_happening = False
    elif not first_time_happening:
        global relay_to_timer
        relay_to_timer = scheduler.enter(5, 2, timer)
        try:
            scheduler.run()
        except AllDoneException:
            pass

并在函数中 timer

    if terminate:
        raise AllDoneException