0

Цель: Запустить таймер для внутреннего цикла и в случае не успевании завершить внутренний цикл.

import threading

crit = False

def Timeout(): 
   crit = True

my_timer = threading.Timer(60.0, Timeout)

while True:
    #code...
    my_timer.start()
    while True:
        if crit == True:
            #code...
            my_timer.cancel()
            break

Ошибка:

threads can only be started once.

2
  • Плохо понятно. Поподробнее, пожалуйста. 5 июн 2019 в 6:54
  • У меня подобной ошибки нет. Один раз выполняется внешний while и потом бесконечно внутренний не заходя в if. 5 июн 2019 в 6:58

1 ответ 1

1

threading.Timer выполняется только один раз, а cancel() только отменяет вызов таймера, поэтому попробуйте создавать и запускать таймер на каждой итерации:

import threading

crit = False

def on_timeout():
    global crit
    crit = True
    print('on_timeout:', crit)

while True:
    my_timer = threading.Timer(5, on_timeout)
    my_timer.start()

    while True:
        if crit:
            print('Crit!')

            crit = False
            break

Сделал таймер на основе threading.Timer и теперь он в цикле выполняет вызов указанной функции:

import threading

crit = False

class LoopTimer(threading.Thread):
    def __init__(self, interval, function, args=None, kwargs=None):
        super().__init__()
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = threading.Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        while not self.finished.is_set():
            self.finished.wait(self.interval)
            self.function(*self.args, **self.kwargs)

def on_timeout():
    global crit
    crit = True
    print('on_timeout:', crit)

my_timer = LoopTimer(5, on_timeout)
my_timer.start()

while True:
    if crit:
        print('Crit!')

        crit = False
        # my_timer.cancel()

А вызов my_timer.cancel() завершит выполнение потока

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.