思路源自: StackOverflow Core:

class BackgroundTasks(threading.Thread):
    __task = None

    def Stop(self):
        self.__task = None

    def __init__(self, task):
        super().__init__()
        self.__task = task

    def run(self, *args, **kwargs):
        while True:
            if self.__task is None:
                break

            self.__task()
            time.sleep(0.5)

测试代码:

# 等待一会还在准备好的状态,那就说明号可能被禁止游戏了
EndTime = 5

cTime = time.time()

def __check():
    if lobby.GetState() == State.Dota2Ready:
        if (time.time() - cTime) >= EndTime:
            print(userName, " 可能被禁赛了,进手动查看....")
            bTask.Stop()
    pass

bTask = BackgroundTasks(__check)
bTask.start()

def exitApp(signum, frame):
    bTask.Stop()
    exit()

signal.signal(signal.SIGINT, exitApp)
signal.signal(signal.SIGTERM, exitApp)