python定时器apscheduler模块实例用法讲解以及代码案例(python定时任务APScheduler使用教程详解)

python定时器apscheduler模块实例用法讲解以及代码案例(python定时任务APScheduler使用教程详解)

python编程admin2022-08-24 14:00:0941A+A-

1.简介

apschedulerpython中的任务定时模块,它包含四个组件:触发器(trigger),作业存储(job store),执行器(executor),调度器(scheduler).

2.安装

pip install apscheduler

3.示例

from apscheduler.schedulers.blocking import BlockingScheduler
#作业1
def my_job1():
    print ('hello world!')
#作业2
def my_job2(name):
    print ('hello world,', name)
# 每个五秒运行一次函数
sched = BlockingScheduler()
#不带参数和和带有参数的函数
sched.add_job(my_job1, 'interval', seconds=5)
sched.add_job(func=my_job2, args=('tom',), trigger='interval', seconds=5)
sched.start()

在这里插入图片描述

4.讲解

关于触发器(trigger),它有三种参数可选:date / interval / cron.

date:一次性任务,即只执行一次任务。

参数如下:

next_run_time (datetime|str) – the date/time to run the job at
timezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already

示例如下:

# 延时五秒后执行一次
sched.add_job(func=my_job2, args=('tom',), trigger='date', next_run_time=now+datetime.timedelta(seconds=5))

interval:循环任务,即按照时间间隔执行任务。

参数如下:

weeks (int) – number of weeks to wait
days (int) – number of days to wait
hours (int) – number of hours to wait
minutes (int) – number of minutes to wait
seconds (int) – number of seconds to wait
start_date (datetime|str) – starting point for the interval calculation
end_date (datetime|str) – latest possible date/time to trigger on
timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations

示例如下:

#每隔五秒执行一次任务
sched.add_job(func=my_job2, args=('tom',), trigger='interval', seconds=5)

cron:定时任务,即在每个时间段执行任务。

参数如下:

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
year (int|str) – 4-digit year
month (int|str) – month (1-12)
day (int|str) – day of the (1-31)
week (int|str) – ISO week (1-53)
day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
hour (int|str) – hour (0-23)
minute (int|str) – minute (0-59)
second (int|str) – second (0-59)
start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)
end_date (datetime|str) – latest possible date/time to trigger on (inclusive)
timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)

在这里插入图片描述
示例如下:

#在1-3,8-10月,每天的下午5点,每一分钟执行一次任务
sched.add_job(func=my_job1, trigger='cron', month='1-3,8-10', day='*', hour='17', minute='\*')

点击这里复制本文地址 以上内容来源于互联网,由爱搜问收集整理,如有侵权请联系站长,核实后立即删除,转载分享时注明本文地址!

支持Ctrl+Enter提交
qrcode

爱搜问 ©2021-2022 吉ICP备2022002266号 Aisouwen.COM.
站点地图1 站点地图2 站点地图3