📝 Docs: 调整跨插件访问文档 (#993)

Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
This commit is contained in:
AkiraXie
2022-05-21 11:17:27 +08:00
committed by GitHub
parent 2fbd44eef9
commit 5924f1e7ac
12 changed files with 55 additions and 142 deletions

View File

@ -1,4 +1,7 @@
---
sidebar_position: 1
description: 在 NoneBot2 中使用定时任务
options:
menu:
weight: 20
@ -13,7 +16,7 @@ options:
## 从 NoneBot v1 迁移
`APScheduler` 作为 NoneBot v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。NoneBot2 已将 `APScheduler` 独立为 nonebot_plugin_apscheduler 插件,你可以在[商店](https://v2.nonebot.dev/store.html)中找到它。
`APScheduler` 作为 NoneBot v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。NoneBot2 已将 `APScheduler` 独立为 nonebot_plugin_apscheduler 插件,你可以在[商店](/store)中找到它。
相比于 NoneBot v1NoneBot v2 只需要安装插件并修改 `scheduler` 的导入方式即可完成迁移。
@ -40,21 +43,23 @@ poetry add nonebot-plugin-apscheduler
```
:::tip 提示
由于稍后我们将使用 `nonebot.require()` 方法进行导入,所以无需额外的 `nonebot.load_plugin()`
由于稍后我们将使用 `nonebot.require()` 方法进行声明依赖,所以无需额外的 `nonebot.load_plugin()`
:::
## 快速上手
1. 在需要设置定时任务的插件中,通过 `nonebot.require` 从 nonebot_plugin_apscheduler 导入 `scheduler` 对象
2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务
1. 在需要设置定时任务的插件中,通过 `nonebot.require` 声明插件依赖
2. 从 nonebot_plugin_apscheduler 导入 `scheduler` 对象
3. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务
将上述步骤归纳为最小实现的代码如下:
```python
```python {3,5}
from nonebot import require
scheduler = require("nonebot_plugin_apscheduler").scheduler
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler
@scheduler.scheduled_job("cron", hour="*/2", id="xxx", args=[1], kwargs={"arg2": 2})
async def run_every_2_hour(arg1, arg2):
@ -69,16 +74,16 @@ scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx"
为了使插件能够实现定时任务,需要先将 `scheduler` 对象导入插件。
NoneBot2 提供了 `nonebot.require` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。
NoneBot2 提供了 `nonebot.require` 方法来实现声明插件依赖,确保 `nonebot_plugin_apscheduler` 插件可以在使用之前被导入。声明完成即可直接通过 import 导入 `scheduler` 对象。
NoneBot2 使用的 `scheduler` 对象为 `AsyncIOScheduler` 。
> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅[这里](./export-and-require.md)
```python
```python {3,5}
from nonebot import require
scheduler = require("nonebot_plugin_apscheduler").scheduler
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler
```
### 编写定时任务