From 4a890298dbaef8e99c3f0dd25d71474231f8b015 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sat, 12 Sep 2020 13:34:36 +0800 Subject: [PATCH] :sparkles: add apscheduler --- nonebot/__init__.py | 11 +++++++++++ nonebot/config.py | 10 ++++++++++ nonebot/sched.py | 12 ++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 nonebot/sched.py diff --git a/nonebot/__init__.py b/nonebot/__init__.py index 5e7a2034..4a15bd6a 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -108,6 +108,7 @@ def get_bots() -> Union[NoReturn, Dict[str, Bot]]: return driver.bots +from nonebot.sched import scheduler from nonebot.config import Env, Config from nonebot.log import logger, default_filter from nonebot.adapters.cqhttp import Bot as CQBot @@ -169,6 +170,9 @@ def init(*, _env_file: Optional[str] = None, **kwargs): logger.debug("Loading nonebot test frontend...") nonebot_test.init() + if scheduler: + _driver.on_startup(_start_scheduler) + def run(host: Optional[str] = None, port: Optional[int] = None, @@ -201,6 +205,13 @@ def run(host: Optional[str] = None, get_driver().run(host, port, *args, **kwargs) +async def _start_scheduler(): + if scheduler and not scheduler.running: + scheduler.configure(_driver.config.apscheduler_config) + scheduler.start() + logger.opt(colors=True).info("Scheduler Started") + + from nonebot.plugin import on_message, on_notice, on_request, on_metaevent from nonebot.plugin import on_startswith, on_endswith, on_command, on_regex from nonebot.plugin import load_plugin, load_plugins, load_builtin_plugins, get_loaded_plugins diff --git a/nonebot/config.py b/nonebot/config.py index 5ecc93e6..b56576a7 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -237,6 +237,16 @@ class Config(BaseConfig): SESSION_EXPIRE_TIMEOUT=[DD ][HH:MM]SS[.ffffff] SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601 """ + apscheduler_config: dict = {"apscheduler.timezone": "Asia/Shanghai"} + """ + - 类型: ``dict`` + - 默认值: ``{"apscheduler.timezone": "Asia/Shanghai"}`` + - 说明: + APScheduler 的配置对象,见 `Configuring the Scheduler`_ + + .. _Configuring the Scheduler: + https://apscheduler.readthedocs.io/en/latest/userguide.html#configuring-the-scheduler + """ # custom configs # custom configs can be assigned during nonebot.init diff --git a/nonebot/sched.py b/nonebot/sched.py new file mode 100644 index 00000000..cc54ac1e --- /dev/null +++ b/nonebot/sched.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +try: + from apscheduler.schedulers.asyncio import AsyncIOScheduler +except ImportError: + AsyncIOScheduler = None + +if AsyncIOScheduler: + scheduler = AsyncIOScheduler() +else: + scheduler = None