APScheduler(Python)定时框架入门

一颗蔬菜 2019-06-24 AM 71℃ 0条
前言

想写一个每天在固定时间爬取必应壁纸并对Windows系统壁纸进行更换的小程序部署到服务器,拜读了biglao的博客,站在巨人的肩膀人学习一下APScheduler。做一个Programmer的乐趣就是能用code做一些快乐的事情吧。

间隔性任务
# -*- coding: utf-8 -*-
# @Time    : 2019/6/24 7:05
# @Author  : 2simple
# @Site    : 时间间隔型任务
# @File    : demo-1.py
# @Software: PyCharm

from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    # 若当前OS为NT则按Ctrl+Break键退出,否则按Ctrl+C,部分不带小键盘的笔记本电脑上没有break键
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

参数

  • 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

demo-1运行结果.png

定时性任务
# -*- coding: utf-8 -*-
# @Time    : 2019/6/24 7:42
# @Author  : 2simple
# @Site    : 定时性任务
# @File    : demo-2.py
# @Software: PyCharm


from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    # 每天8:48执行任务
    scheduler.add_job(tick, 'cron', hour=8, minute=48)
    print('OS is {0} ,Press Ctrl+{1} to exit'.format(os.name, 'Break' if os.name == 'nt' else 'C    '))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

参数:

  • 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)

demo-2运行结果.png

标签: 爬虫

非特殊说明,本博所有文章均为博主原创。

上一篇 实习一周总结
下一篇 Python Bugs