Я хочу вызывать функцию в цикле основного потока каждые N секунд.
Для этого Threading.Timer инициализируется функцией _timer_handler ().Эта функция вызывается в контексте потока таймера, я пытаюсь вызвать _refresh_token () в цикле основного потока, но она никогда не вызывается.
# coding: utf-8
import asyncio
import datetime
import time
import threading
def thread_msg(msg):
print("{} - Current Thread is {} | {} |".format(datetime.datetime.now(), threading.current_thread().ident, threading.current_thread().name), msg)
class My_Session():
def __init__(self, delay=30):
self._timer = None
self._delay = delay
self._loop = asyncio.get_event_loop()
def start(self):
thread_msg("Start session")
self._init_timer()
def stop(self):
if self._timer:
self._timer.cancel()
thread_msg("Stop session")
def _init_timer(self):
self._timer = threading.Timer(self._delay, self._timer_handler)
print("Set timer to {} seconds to refresh token".format(self._delay))
self._timer.start()
def _timer_handler(self):
try:
thread_msg("Time out, call self._refresh_token")
self._loop.call_soon_threadsafe(self._refresh_token)
thread_msg("call self._refresh_token done")
except Exception as e:
thread_msg("Exception in _timer_handler: {}".format(e))
def _refresh_token(self):
thread_msg("_refresh_token is called properly,\n reinitialize the timer...")
self._init_timer()
if __name__ == '__main__':
thread_msg("Start script")
session = My_Session(5)
session.start()
try:
while True:
thread_msg("loop")
time.sleep(1)
except KeyboardInterrupt:
session.stop()
Вывод:
2019-06-24 20:21:29.776809 - Current Thread is 10220 | MainThread | Start script
2019-06-24 20:21:29.777906 - Current Thread is 10220 | MainThread | Start session
Set timer to 5 seconds to refresh token
2019-06-24 20:21:29.778310 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:30.787545 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:31.791333 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:32.794627 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:33.806744 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:34.790288 - Current Thread is 17148 | Thread-1 | Time out, call self._refresh_token
2019-06-24 20:21:34.790573 - Current Thread is 17148 | Thread-1 | call self._refresh_token done
2019-06-24 20:21:34.820744 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:35.822738 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:36.830907 - Current Thread is 10220 | MainThread | loop
2019-06-24 20:21:37.833233 - Current Thread is 10220 | MainThread | loop