版权声明:风火编程, 欢迎指正. https://blog.csdn.net/weixin_42620314/article/details/82789601
python定时任务
指定时间长度后执行的单次任务
DEMO (5s后执行)
import time
from threading import Timer
def func(msg, starttime):
print( '程序启动时刻:', starttime, '当前时刻:', time.time(), '消息内容 --> %s' % (msg))
timer = Timer(5, func, ('hello world', time.time()))
timer.start()
固定时间点执行的循环任务
DEMO (每次秒针指向5s时执行)
from apscheduler.schedulers.background import BackgroundScheduler
total = 0
def print_job():
global total
total += 1
print("print_job start.total = {} times".format(total))
if __name__ == '__main__':
scheduler = BackgroundScheduler()
# 周一到周五每分钟的05s执行一次
scheduler.add_job(print_job, 'cron', second=0, minute='*', hour='*', day='*', month='*', day_of_week='mon-fri', year='*')
scheduler.start()
固定时间间隔执行的循环任务
DEMO (每小时执行)
import time
from apscheduler.schedulers.background import BackgroundScheduler
INTERVAL = 1 * 60 * 60 # 时间间隔,单位:秒
total = 0
def print_job():
global total
total += 1
print("print_job start.total = {} times".format(total))
if __name__ == '__main__':
scheduler = BackgroundScheduler()
scheduler.add_job(print_job, 'interval', seconds=INTERVAL)
scheduler.start()
while True:
time.sleep(1024)