方法一、用time模块中的sleep方法
import datetime
import time
def do_job():
while True:
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(2)
if __name__ == '__main__':
do_job()
输出结果:
2020-01-17 23:41:28
2020-01-17 23:41:30
2020-01-17 23:41:32
2020-01-17 23:41:34
2020-01-17 23:41:36
2020-01-17 23:41:38
2020-01-17 23:41:40
方法二、用python线程(threading)的Timer模块
import datetime
import threading
def do_job():
# threading.Timer(2,do_job,())
# 第一个参数: 延迟多长时间执行任务(单位: 秒)
# 第二个参数: 要执行的任务, 即函数
# 第三个参数: 调用函数的参数(tuple)
global timer
print(datetime.datetime.now().strftime("%H-%m-%d %H:%M:%S"))
timer = threading.Timer(2, do_job, ())
timer.start()
if __name__ == '__main__':
do_job()
输出结果
00-01-18 00:06:14
00-01-18 00:06:16
00-01-18 00:06:18
00-01-18 00:06:20
00-01-18 00:06:22
00-01-18 00:06:24
网上有资料说这个方法要用 global 这个关键字,不使用的话会造成线程堆积,最终程序退出 ,经过测试这是没有必要的。测试方法如下:
import datetime
import threading
def do_job(num):
# threading.Timer(2,do_job,())
# 第一个参数: 延迟多长时间执行任务(单位: 秒)
# 第二个参数: 要执行的任务, 即函数
# 第三个参数: 调用函数的参数(tuple)
# global timer
num += 1
print("do_job 执行的次数:", num)
print("当前线程数:{}".format(threading.active_count()))
print("\n")
if num > 4:
return
print(datetime.datetime.now().strftime("%H-%m-%d %H:%M:%S"))
timer = threading.Timer(2, do_job, (num,))
timer.start()
if __name__ == '__main__':
do_job(0)
输出结果
do_job 执行的次数: 1
当前线程数:1
00-01-18 00:15:41
do_job 执行的次数: 2
当前线程数:2
00-01-18 00:15:43
do_job 执行的次数: 3
当前线程数:2
00-01-18 00:15:45
do_job 执行的次数: 4
当前线程数:2
00-01-18 00:15:47
do_job 执行的次数: 5
当前线程数:2
由此可以证明:不加global 当前活跃的线程数并没有增加!因此global是没有必要的
注:threading.active_count()是用来显示当前活跃的进程数。
方法三、使用标准库中sched模块
sched 是事件调度器,通过 scheduler 类来调度事件,从而达到定时执行任务的效果,用法如下:
import sched
import time
# 生成调度器
scheduler = sched.scheduler(time.time, time.sleep)
def print_event(name):
print('EVENT:', time.time(), name)
print('START:', time.time())
# 分别设置在执行后2秒、3秒之后执行调用函数
scheduler.enter(2, 1, print_event, ('first',))
scheduler.enter(3, 1, print_event, ('second',))
# 运行调度器
scheduler.run()
输出结果
START: 1579278724.9186893
EVENT: 1579278726.9192598 first
EVENT: 1579278727.920072 second
sched模块是python标准时间调度器,后续会专门详细讲解用法。也可关注本人公众号:DeepLearning大讲堂