APScheduler包——python实现定时任务

本文介绍了如何结合Tornado Web框架与APScheduler库创建一个每天7点执行的定时任务。在运行过程中遇到了Pytz库的弃用警告,通过设置时区参数`timezone='Asia/Shanghai'`成功解决。示例代码展示了初始化调度器和启动HTTP服务器的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

APScheduler+tornado的使用:

# -*- coding: utf-8 -*-

"""
@Author  : Pink
@Time    : 12/29/2021 2:48 PM
@Function: 
"""
import time
from tornado import web, ioloop
from tornado.httpserver import HTTPServertime_create_delta
from settings.settings import settings
from settings.urls import urls
from apscheduler.schedulers.tornado import TornadoScheduler


def hello():
    print('hello')


def init_scheduler():
    scheduler = TornadoScheduler(timezone='Asia/Shanghai')
    # 定时每天7点0分0秒 执行一次hello函数  next_run_time的意思是从什么时候开始
    # scheduler.add_job(hello, "cron", hour=7, minute=0, second=0, next_run_time=datetime.now())
    scheduler.add_job(hello, "cron", hour=7, minute=0, second=0)
    scheduler.start()


def make_app():
    app = web.Application(urls, **settings)
    return app


if __name__ == '__main__':
    init_scheduler()
    app = make_app()
    server = HTTPServer(app)
    server.bind(8081)
    server.start(1)
    ioloop.IOLoop.current().start()

使用apscheduler遇到的问题

PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
if obj.zone == 'local':

PytzUsageWarning: The normalize method is no longer necessary, as this time zone supports the fold attribute (PEP 495). For more details on migrating to a PEP 495-compliant implementation, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
return self.timezone.normalize(dateval + difference), fieldnum

PytzUsageWarning: The localize method is no longer necessary, as this time zone supports the fold attribute (PEP 495). For more details on migrating to a PEP 495-compliant implementation, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
return self.timezone.localize(datetime(**values))

 解决方法:添加时区

scheduler = TornadoScheduler(timezone='Asia/Shanghai')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值