使用threading模块中的Timer函数
from threading import Timer
import time
def execute_func(name, age, gender, hobby):
print(f"name is {name}, age is {age}, gender is {gender}, hobby is {hobby}")
def start_func():
# Timer接收的参数是:interval, function, args=None, kwargs=None
# interval:时间间隔,一个数字,表示多少秒后执行
# function:函数,要执行的函数
# args:位置参数
# kwargs:关键字参数
t = Timer(3, execute_func, args=("satori", 10), kwargs={"gender": "f", "hobby": "animal"})
# 调用start之后启动,并且不会阻塞,因为单独开启了一个线程
t.start()
time.sleep(5)
print("在我打印之前,execute_func函数就已经被执行完毕了")
start_func()
运行结果
name is satori, age is 10, gender is f, hobby is animal
在我打印之前,execute_func函数就已经被执行完毕了
使用schedule模块
import schedule
def foo():
print(123)
# 每隔3秒钟运行foo,如果有参数,直接通过args= 或者kwargs=进行传参即可
schedule.every(3).seconds.do(foo)
# 每隔1秒钟运行foo
schedule.every().seconds.do(foo)
# 每隔1分钟运行foo
schedule.every().minutes.do(foo)
# 每隔一小时运行foo
schedule.every().hours.do(foo)
# 每隔一天运行foo
schedule.every().days.do(foo)
# 每隔一星期运行foo
schedule.every().weeks.do(foo)
# 每隔3到5秒钟运行foo
schedule.every(3).to(5).seconds.do(foo)
# 每隔3到5天运行foo
schedule.every(3).to(5).days.do(foo)
# 每天在10:30的时候运行foo
schedule.every().days.at("10:30").do(foo)
# 每周一的时候运行foo
schedule.every().monday.do(foo)
# 每周日晚上11点的时候运行foo
schedule.every().sunday.at("23:00").do(foo)
while True:
# 保持schedule一直运行,然后去查询上面的任务
schedule.run_pending()
import schedule
import time
def foo1():
time.sleep(2)
print(time.perf_counter() - start_time)
def foo2():
time.sleep(2)
print(time.perf_counter() - start_time)
schedule.every(5).seconds.do(foo1)
schedule.every(5).seconds.do(foo2)
start_time = time.perf_counter()
while 1:
schedule.run_pending()
运行结果
7.000133540999999
9.000496485
14.001490562999999
16.002477991
21.002556953
23.003146251
28.003308606
30.003953593
注意到:运行时间是每隔七秒后,由于任务本身也占用了时间。可以考虑使用多线程
import schedule
import time
import threading
def foo1():
time.sleep(2)
print(time.perf_counter() - start_time)
def foo2():
time.sleep(2)
print(time.perf_counter() - start_time)
def t1():
t = threading.Thread(target=foo1)
t.start()
def t2():
t = threading.Thread(target=foo2)
t.start()
schedule.every(5).seconds.do(t1)
schedule.every(5).seconds.do(t2)
start_time = time.perf_counter()
while 1:
schedule.run_pending()
运行结果
7.006393073
7.006451532000001
12.007217038999999
12.012260847999999
17.00669922
17.012707463
22.008171498000003
22.008225246000002
可以看到这次变成每隔5秒执行了,而且两个任务之间也没有2s的间隔了