You need to enable JavaScript to run this app. 如何使用aiocron为Discord.py机器人配置定时任务实现每5-8小时自动重启
优惠活动
大模型
产品
解决方案
定价
更多

如何使用aiocron为Discord.py机器人配置定时任务实现每5-8小时自动重启

实现方案:aiocron定时随机重启+原有任务优化

discord.py内置的tasks.loop遇到未捕获异常、网络波动导致协程挂死时会静默停止,这是你遇到任务无报错停掉的核心原因,5-8小时随机重启属于可行的临时兜底方案,具体实现如下:


1. 依赖安装

执行命令安装需要的工具包:

pip install aiocron

2. 随机自动重启逻辑实现

在机器人主文件中加入以下代码,可实现每次启动后随机5-8小时自动重启进程:

import aiocron
import random
import os
import sys
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f"已登录为 {bot.user}")
    # 注册自动重启定时任务
    @aiocron.crontab('*/1 * * * *', start=False)
    async def auto_restart():
        # 首次启动初始化下次重启时间
        if not hasattr(bot, 'next_restart_timestamp'):
            delay_hour = random.uniform(5, 8)
            bot.next_restart_timestamp = bot.loop.time() + delay_hour * 3600
            print(f"下次自动重启将在{delay_hour:.1f}小时后执行")
        # 到点触发重启
        if bot.loop.time() >= bot.next_restart_timestamp:
            print("开始执行自动重启")
            await bot.close()
            # 替换当前进程重启机器人,假设启动文件名为main.py,若用systemd/pm2管理可直接exit(0)由外部工具拉起
            os.execv(sys.executable, [sys.executable] + sys.argv)
    auto_restart.start()

# 其他原有逻辑
bot.run("你的机器人Token")

3. 原有自动发帖任务优化

你贴出的代码缺少全量异常捕获,很容易触发任务静默退出,优化后的代码如下:

from discord.ext import tasks
import json
import asyncio
import nekos

@tasks.loop(minutes=2.5)
async def autoh(self):
    await self.bot.wait_until_ready()
    try:
        with open("autoposting.json", 'r') as f:
            auto = json.load(f)

        embed = discord.Embed(
            title="Enjoy your poggers porn lmao",
            description=f"Posting can be slow, please take into consideration how many servers this bot is in and how many are using auto posting. Please be patient. If I completely stop posting, please rerun the command or join the support server.\n[Add me]({Invite}) | [Join the server]({Server}) | [Vote]({Vote})", 
            colour=EMBED_COLOUR
        )
        try:
            embed.set_image(url=(await self.get_hentai_img()))
        except nekos.errors.NothingFound:
            print("no image found")
            return

        for entry in auto.items():
            entry_data = entry[1]
            if "hentai_channel" not in entry_data:
                continue
            channel = self.bot.get_channel(entry_data["hentai_channel"])
            await asyncio.sleep(2)
            if not channel:
                continue
            try:
                if not channel.is_nsfw():
                    await channel.send("This channel seems to not be NSFW anymore.\nThis message will continually repeat until you fix this issue.")
                else:
                    await channel.send(embed=embed)
            except discord.Forbidden:
                try:
                    await channel.guild.owner.send(f"I was unable to autopost due to missing permissions in {channel.guild.name}, please check that the channel still exists and that I have the permission to post to it.\nThis message will continually repeat until you fix the issue at hand.")
                except:
                    pass
            except (discord.HTTPException, discord.NotFound):
                pass
    except Exception as e:
        print(f"自动发帖任务异常:{str(e)}")

# 任务异常退出自动重启钩子
@autoh.after_loop
async def after_autoh(self):
    if autoh.failed():
        print("自动发帖任务异常退出,5秒后重启任务")
        await asyncio.sleep(5)
        autoh.start(self)

注意事项

  • 若使用pm2、systemd等进程管理工具托管机器人,可删除os.execv相关代码,重启逻辑改为直接退出进程,由外部工具自动拉起,稳定性更高
  • 自动重启前可根据业务需要添加内存数据落盘逻辑,避免运行时数据丢失
  • 优先依赖任务本身的异常自愈逻辑,自动重启仅作为兜底方案使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:09:00