nonebot / plugin-apscheduler

APScheduler Support for NoneBot2
https://nonebot.dev/docs/best-practice/scheduler
MIT License
83 stars 9 forks source link

提问:如何以driver.on_bot_connect的方式启动定时任务 #36

Closed Agnes4m closed 1 year ago

Agnes4m commented 1 year ago

如果不是on_bot_connect方式是正常启动的。

现在我希望改到连接bot后启动定时任务

@driver.on_bot_connect
async def _()
    users = read_yaml(Path().joinpath("data/bilifan"))
    cron = users.get("CRON", None)
    if not cron:
        logger.error("定时格式不正确,不启用定时功能")
    try:
        fields = cron.split(" ")
        scheduler.add_job(auto_cup, "cron", hour=fields[0], minute=fields[1], id="auto_cup")
    except AttributeError:
        logger.error("定时格式不正确,不启用定时功能")

结果在启动的时候报错(之前还有另外一种报错,说该定时任务已经存在,没法复现暂时) image

yanyongyu commented 1 year ago

两种方式:

  1. 你可以在你的定时任务中判断是否有bot已链接
  2. 在bot连接的时候添加任务,并且在bot断开的时候移除任务。如果有多个bot连接请自行判断任务是否已存在是否需要移除和添加
Agnes4m commented 1 year ago

那么我就用第二个方法,如下是否正确

@driver.on_bot_disconnect
async def _():
    scheduler.remove_job(auto_cup)
yanyongyu commented 1 year ago

少了引号

Agnes4m commented 1 year ago

我理解错误在哪里了。如果定时任务为:

async def auto_cup():
    ...

那么添加和删除应该是

scheduler.add_job(auto_cup, "cron", hour=fields[0], minute=fields[1], id="auto_cup")
scheduler.remove_job("auto_cup")

对于多Bot连接产生的多个定时任务,可以把bot相关信息加到id里,对吧

yanyongyu commented 1 year ago

可以的