如何关闭task_1discord.py

问题描述 投票:0回答:1

我需要关闭task_1我尝试使用close(),logout()和serch来解决我的问题我不知道

import discord
import asyncio
from asyncio import create_task, run

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

async def main():
    task_1 = create_task(MyClient().start("Token"))
    await asyncio.sleep(30)
    task_2 = create_task(MyClient().start("Token"))

    await task_1
    await task_2

if __name__ == '__main__':
    run(main())
python discord
1个回答
0
投票

您可以在任务上使用 cancel() 方法。

async def main():
    task_1 = create_task(MyClient().start("Token"))
    await asyncio.sleep(30)
    task_1.cancel()  # Cancel task_1 after 30 seconds

    # Wait for task_1 to be cancelled
    try:
        await task_1
    except asyncio.CancelledError:
        print("Task task_1 cancelled")

    # Start task_2 after task_1 is cancelled
    task_2 = create_task(MyClient().start("Token"))
    await task_2
© www.soinside.com 2019 - 2024. All rights reserved.