与Python的其他Coroutine一起运行Aioschedule

发布于 2025-02-09 08:33:00 字数 687 浏览 3 评论 0原文

我有两个Coroutines使用 aioschedule 。这是我的代码,

import aioschedule as schedule
import asyncio

async def foo():
    while True:
        print('foooooo')
        await asyncio.sleep(5)

async def bar():
    while True:
        print('bar')
        await asyncio.sleep(1)

schedule.every(2).seconds.do(bar)

loop = asyncio.get_event_loop()
loop.create_task(schedule.run_pending())
loop.create_task(foo())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()

我想要的是,当其他任务运行时,每秒钟都应该打印bar,但输出仅为foooooo。我想念什么吗?

I have two coroutines one of which is using aioschedule. This is my code

import aioschedule as schedule
import asyncio

async def foo():
    while True:
        print('foooooo')
        await asyncio.sleep(5)

async def bar():
    while True:
        print('bar')
        await asyncio.sleep(1)

schedule.every(2).seconds.do(bar)

loop = asyncio.get_event_loop()
loop.create_task(schedule.run_pending())
loop.create_task(foo())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()

What i want is it should printed bar every n seconds when other task is running but the output is only foooooo. Am i missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没企图 2025-02-16 08:33:00

尝试以下操作:

   import aioschedule as schedule
   import asyncio

   async def foo():
       while True:
           print('foooooo')
           await asyncio.sleep(5)

    async def bar():
        while True:
            print('bar')
            await asyncio.sleep(1)

    #schedule.every(2).seconds.do(bar) <---removed line

    loop = asyncio.get_event_loop()
    loop.create_task(schedule.run_pending())
    loop.create_task(foo())
    loop.create_task(bar()) #<---- added line

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.stop()

try this:

   import aioschedule as schedule
   import asyncio

   async def foo():
       while True:
           print('foooooo')
           await asyncio.sleep(5)

    async def bar():
        while True:
            print('bar')
            await asyncio.sleep(1)

    #schedule.every(2).seconds.do(bar) <---removed line

    loop = asyncio.get_event_loop()
    loop.create_task(schedule.run_pending())
    loop.create_task(foo())
    loop.create_task(bar()) #<---- added line

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.stop()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文