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

如何在asyncio中让两个异步任务独立无限运行?

解决asyncio中两个异步任务独立无限运行的问题

问题分析

你的代码里,sender函数通过外层while True循环,每次同时启动clean和garden任务,再用asyncio.gather等待两个任务全部完成后才进入下一次循环。这就导致两个任务必须同步等待耗时更长的那个完成,才能再次启动,无法实现独立运行的需求。

解决方案

让每个任务自身实现无限循环逻辑,而非在外层统一控制重启。这样两个任务会按照各自的周期独立执行,互不等待。

修改后的完整代码

import asyncio
from pyrogram import Client
from art import *
from datetime import datetime
from colorama import Fore, just_fix_windows_console
from pyrogram import enums
from tqdm import tqdm

just_fix_windows_console()

bot = '#'

api_id = # 替换为你的api_id
api_hash = '#'
app = Client("ava", api_id, api_hash)


def current_time():
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), end='')
    return ''


async def clean(client, mes):
    # 任务自身加入无限循环
    while True:
        print(Fore.LIGHTWHITE_EX)
        for _ in tqdm(range(10)):
            await asyncio.sleep(1)
        await client.send_message(bot, mes, parse_mode=enums.ParseMode.DISABLED)


async def garden(client, mes):
    # 任务自身加入无限循环
    while True:
        print(Fore.LIGHTWHITE_EX)
        for _ in tqdm(range(15)):
            await asyncio.sleep(1)
        await client.send_message(bot, mes, parse_mode=enums.ParseMode.DISABLED)


async def main():
    if input('\n 1. Запустить \n\n >>> ') == '1':
        print(Fore.WHITE)
        print(f' {current_time()} | Соединение с Telegram...')
        await asyncio.sleep(1)
        if app:
            print(Fore.GREEN)
            print(f' {current_time()} | Соединение установлено!')
        else:
            print(Fore.RED)
            print(f' {current_time()} | Произошла ошибка при установке соединения!')
            await asyncio.sleep(10)
            exit()
        await asyncio.sleep(1)
        print(Fore.WHITE + f' {current_time()} | Поиск фрейма...')
        try:
            with open('frame.txt', 'r') as f:
                frame = f.readline()
                if frame == '' or frame == 'put your frame here':
                    print(Fore.RED)
                    print('Пустой фрейм. Убедитесь, что вы заполнили файл frame.txt')
                    await asyncio.sleep(10)
                    exit()
        except FileNotFoundError:
            print(Fore.RED)
            print('Файл фрейма не был найден. Убедитесь в наличии файла frame.txt')
            await asyncio.sleep(10)
            exit()
        if frame:
            await asyncio.sleep(2)
            print(Fore.GREEN + f' {current_time()} | Фрейм был успешно найден!')
            mes1 = f'/clean {frame}'
            mes2 = f'/garden {frame}'
        else:
            print(Fore.RED + f' {current_time()} | Произошла ошибка при поиске фрейма!')
            await asyncio.sleep(10)
            exit()
        await asyncio.sleep(3)
        print(Fore.GREEN + f' {current_time()} | Работа началась!', '\n')
        await sender(mes1, mes2)


async def sender(mes1, mes2):
    async with app:
        # 启动两个独立的无限循环任务,无需外层循环
        task1 = asyncio.create_task(clean(app, mes1))
        task2 = asyncio.create_task(garden(app, mes2))
        # 等待两个任务(无限运行)完成(实际不会结束)
        await asyncio.gather(task1, task2)


def check_sub():
    now = datetime.now()
    sub = datetime(2023, 9, 28)
    if sub > now:
        return True
    else:
        return False


if __name__ == '__main__':
    asyncio.run(app.run(main()))

修改说明

  1. 任务内部添加无限循环:在clean和garden函数内部添加while True,让任务完成一次执行后自动重启,无需外层控制。
  2. 简化sender函数:sender不再需要外层while True,只需启动两个任务并通过asyncio.gather等待它们运行(因为任务本身是无限循环,gather会一直等待)。

这样修改后,clean会每10秒左右执行一次,garden每15秒左右执行一次,两者完全独立,不会互相等待对方完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:52:20