定时器场景
from threading import Timer
class CustomTimer(Timer):
def run(self): while not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.wait(self.interval) class Command(BaseCommand): def handle(self, *args, **options): try: if get_execute_flag(): init_conn() timer_list = [ # 市场首页数据缓存 CustomTimer(1.0, timed_refresh_market_home_page_data), # 邀请排行榜活动开关缓存 CustomTimer(1.0, timed_refresh_invite_leaderboard_activity_switch_data), ] # 开始缓存 for t in timer_list: t.start() while True: if not get_execute_flag(): # 取消定时缓存 for t in timer_list: t.cancel() break time.sleep(5) except: write_error_log('main') finally: time.sleep(5)
timer 源码
先分析wait源码
wait使用的时lock的wait