1、使用schedule模块
import time
import schedule
import datetime
def job():
print(datetime.datetime.now(),'I am working...')
schedule.every(10).seconds.do(job,参数) #每10秒执行一次,如果要加参数,只需在job后面加上参数
schedule.every(10).minutes.do(job) # 每10分钟执行一次
schedule.every().hour.do(job) # 每小时执行一次
schedule.every().day.at("10:30").do(job) # 每天十点半执行
schedule.every(5).to(10).minutes.do(job) # 5-10分钟随机执行一次
schedule.every().monday.do(job) # 每周一执行
schedule.every().wednesday.at("13:15").do(job) # 每周三13点15执行
schedule.every().minute.at(":17").do(job) # 应该为每分钟17秒时执行,没试过
while True:
schedule.run_pending()
time.sleep(1)

2、使用threading.time()
threading.Timer(interval, function, args=[], kwargs={})
interval 是时间间隔,function 是可调用的对象,args 和 kwargs 会作为 function 的参数。
import threading
import datetime
interval_time=3
def test(ms):
now=datetime.datetime.now()
now_new=now.strftime('%Y-%m-%d %H:%M:%S')
print(f'{now_new}:I love you python')
threading.Timer(ms,test,[ms,]).start() #[ms,]作为test()的参数
if __name__ == '__main__':
print('任务开始:',datetime.datetime.now())
test(interval_time)
console:
任务开始: 2020-02-18 09:55:42.166642
2020-02-18 09:55:42:I love you python
2020-02-18 09:55:45:I love you python
2020-02-18 09:55:48:I love you python
2020-02-18 09:55:51:I love you python
2020-02-18 09:55:54:I love you python
PS:觉得这篇文章有用的朋友,多多点赞打赏哦~!
网友评论