Relative front of several python thread content, the content of the film is relatively simple, timer - as the name implies, necessarily for regular tasks.
A Thread Timer Timer principle
Principle is simple, after a specified time interval start thread! Applicable scene: the completion of regular tasks, such as: timed reminder - alarm clock and so on.
# Import the thread module Import Threading timer = threading.Timer(interval, function, args=None, kwargs=None)
Parameter Description:
interval The - interval timer, task timer is started after an interval of how many seconds (unit: seconds);
function - thread function;
args - thread parameters can pass data tuple type, default is empty (default parameters);
kwargs - thread parameters, data dictionaries can pass, default is empty (default parameters);
II. Use a timer thread
Usage scenarios: Alarm,
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解忧 @Blog(个人博客地址): shuopython.com @WeChat Official Account(微信公众号):猿说python @Github:www.github.com @File:python_timer.py @Time:2019/10/22 21:25 @Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累! """ # 导入线程模块 import threading def thread_Timer(): print("该起床啦...5秒之后再次呼叫你起床...") # 声明全局变量 global t1 # 创建并初始化线程 t1 = threading.Timer(5,thread_Timer) # 启动线程 t1.start() if __name__ == "__main__": # 创建并初始化线程 t1 = threading.Timer(5, thread_Timer) # 启动线程 t1.start()
Output:
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Get out of bed ... 5 seconds after the call again you get up ...
Code analysis:
In the main thread creates a thread timer, perform thread_Timer thread function after 5 seconds, and when thread_Timer end of the function, but also set a timer thread thread_Timer, which completed a recursive operation, repeat the timing interval of 5 seconds task!
III. Key summary
There are many ways to interact with the thread of the thread so far has explained the thread mutex Lock , thread the event Event , thread condition variable for condition Condition , thread timer Timer, different needs, use may be different, flexible use!
you may also like:
1.python thread events for Event
2.python thread condition variable Condition
4.python thread creation and parameter passing
Reproduced please specify: ape say Python » Python thread timer Timer