You need to enable JavaScript to run this app. 如何通过指令启动discord.py中的tasks.loop定时循环任务
优惠活动
大模型
产品
解决方案
定价
更多

如何通过指令启动discord.py中的tasks.loop定时循环任务

问题原因及修正方案

你代码里的错误有两处:

  1. Test_lol是直接定义的全局定时任务对象,不属于上下文ctx的属性,不需要通过ctx调用
  2. start()是task的普通调用方法,不需要加await,且你遗漏了方法调用的括号
  3. 额外需要增加运行状态判断,避免重复调用启动方法抛出异常

修正后的代码片段

首先修改timer_start指令的代码:

@client.command()
async def timer_start(ctx):
    # 先判断任务是否已经在运行,避免重复启动报错
    if not Test_lol.is_running():
        Test_lol.start()
        await ctx.send("定时任务已启动")
    else:
        await ctx.send("定时任务已经在运行中,请勿重复启动")

如果希望启动任务后立刻执行一次消息发送,不需要等24小时才触发第一次运行,可以改成如下写法:

@client.command()
async def timer_start(ctx):
    if not Test_lol.is_running():
        # 先手动执行一次任务逻辑
        await Test_lol.callback()
        # 再启动定时循环
        Test_lol.start()
        await ctx.send("定时任务已启动,已触发第一次执行")
    else:
        await ctx.send("定时任务已经在运行中,请勿重复启动")

补充说明

如果后续需要加停止任务的指令,可以用如下写法:

@client.command()
async def timer_stop(ctx):
    if Test_lol.is_running():
        Test_lol.stop()
        await ctx.send("定时任务已停止")
    else:
        await ctx.send("当前没有正在运行的定时任务")

内容的提问来源于stack exchange,提问作者Uouq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 16:27:03