操作系统的版本信息:
[root@centos6 ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[root@centos6 ~]#
[root@centos6 ~]# uname -r
2.6.32-696.el6.x86_64
Python的版本信息:
[root@centos6 ~]# python3 --version
Python 3.6.8
使用Thread类的子类Timer()可以控制指定函数在每隔一段时间后自动执行一次:
例子:
[root@centos6 ~]# cat xx.py
#coding=utf-8
from threading import Timer
import time
def func1():
print('Welcome to zhuohua.')
dt = time.localtime()
print("当前时间:",time.asctime(dt))
def func_main(func,second):
index_1 = 0
while index_1 < 3: #进程执行3次后自动结束
timer = Timer(second,func)
timer.start()
timer.join()
index_1 = index_1 + 1
if __name__ == '__main__':
func_main(func1,2) #每隔2秒后执行一次函数func1()
脚本运行的效果:(程序执行3次后自动结束)
[root@centos6 ~]# python3 xx.py
Welcome to zhuohua.
当前时间: Sat Feb 8 11:45:06 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:45:08 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:45:10 2019
[root@centos6 ~]#
############
############
使用time模块的sleep()函数可以让进程休眠一段时间后再继续执行:
例子:
[root@centos6 ~]# cat xx.py
#coding=utf-8
import time
def func1():
print("Welcome to zhuohua.")
print("当前时间:",time.ctime())
def func_main(func,second):
while True: #进程会无限次地自动执行下去
func()
time.sleep(second)
if __name__ == '__main__':
func_main(func1,3) #每隔3秒后执行一次函数func1()
脚本运行的效果:( 程序会无限次地执行下去; 组合键Ctrl+c可结束程序的执行 )
[root@centos6 ~]# python3 xx.py
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:44 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:47 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:50 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:53 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:56 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:46:59 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:47:02 2019
Welcome to zhuohua.
当前时间: Sat Feb 8 11:47:05 2019
相关文章:
while循环语句
time模块
CentOS6使用Ping
Windows使用Ping
CentOS8使用多线程+Ping |