Python-定时任务框架-APScheduler

工作中有些程序需要定时或者隔一段时间执行一次,比较简单的方法crontab和time模块就可以实现了,不过python有些定时任务框架还是蛮不错的,记录几个比较常用的写法

1.从crontab表达式里获取定时规则

from apscheduler.schedulers.background import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime

scheduler = BlockingScheduler()

def func():
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f'{now} hello world!')

scheduler.add_job(func, CronTrigger.from_crontab('* * * * *'))  # 每隔1分钟执行一次
scheduler.start()
"""
2019-07-23 16:41:00 hello world!
2019-07-23 16:42:00 hello world!
2019-07-23 16:43:00 hello world!
2019-07-23 16:44:00 hello world!
2019-07-23 16:45:00 hello world!

from_crontab底层代码实现逻辑:
    value = '* * * * *'.split()
    minute=values[0], hour=values[1], day=values[2], month=values[3], day_of_week=values[4]
"""

2.使用cron定时触发任务

from apscheduler.schedulers.background import BlockingScheduler
from datetime import datetime

scheduler = BlockingScheduler()

def func():
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f'{now} hello world!')

scheduler.add_job(func, 'cron', second='0')  # 每到0秒执行一次
scheduler.start()
"""
2019-07-23 16:51:00 hello world!
2019-07-23 16:52:00 hello world!
2019-07-23 16:53:00 hello world!
2019-07-23 16:54:00 hello world!
2019-07-23 16:55:00 hello world!

参数: year, month, day, week, day_of_week, hour, minute, second
释义: 年    月      日   周    周几          小时  分钟     秒
"""

3.使用interval周期触发任务

from apscheduler.schedulers.background import BlockingScheduler
from datetime import datetime

scheduler = BlockingScheduler()

def func():
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f'{now} hello world!')

scheduler.add_job(func, 'interval', seconds=1)  # 每隔1秒钟执行一次
scheduler.start()
"""
2019-07-23 16:54:48 hello world!
2019-07-23 16:54:49 hello world!
2019-07-23 16:54:50 hello world!
2019-07-23 16:54:51 hello world!
2019-07-23 16:54:52 hello world!

参数: seconds, minutes, hours
释义: 秒       分钟      小时
"""

你可能感兴趣的:(Python)