You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中@tasks.loop(time参数)任务无法触发,求排查解决

问题原因及解决方案

1. 缺少任务就绪等待逻辑

你的任务在Cog初始化时直接启动,但此时Discord Bot可能还未完成登录、建立连接等就绪流程,导致定时任务的触发逻辑未正确初始化。

解决方法:给任务添加before_loop钩子,等待Bot完全就绪后再启动任务调度:

@my_task.before_loop
async def before_my_task(self):
    await self.bot.wait_until_ready()

2. pytz时区对象兼容性问题

discord.py的tasks.loop(time=...)对pytz的时区对象支持存在兼容性问题,建议改用Python标准库的datetime.timezone.utc替代pytz.UTC。

修改时区定义部分:

from datetime import timezone

utc = timezone.utc
time = datetime.time(hour=10, minute=35, tzinfo=utc)

3. 任务启动时已过当日触发点

如果Bot启动时,你设置的10:35 UTC已经过了当天的时间点,任务会等到第二天的同一时间才触发。测试时可临时将时间设置为当前UTC时间之后的几分钟,确认任务是否正常运行。

完整修正后的代码示例

import datetime
from datetime import timezone
from discord.ext import commands, tasks
from config import TEST_SERVER

utc = timezone.utc
# 测试时可替换为当前UTC时间之后的几分钟,比如datetime.datetime.now(utc).minute +5
time = datetime.time(hour=10, minute=35, tzinfo=utc) 

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.my_task.start()

    def cog_unload(self):
        self.my_task.cancel()

    @tasks.loop(time=time)
    async def my_task(self):
        print("My task is running!")

    @my_task.before_loop
    async def before_my_task(self):
        await self.bot.wait_until_ready()

    @commands.command()
    async def test_ping(self, ctx):
        await ctx.send("Test ping")

async def setup(bot:commands.Bot) -> None:
    await bot.add_cog(MyCog(bot), guild=TEST_SERVER)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:27:10