首页 > 解决方案 > 如何在 Python 中创建异步计时器?

问题描述

我想用 Python 创建一个 30 秒的计时器,async但我不知道该怎么做。

我尝试使用此代码,但它阻止了所有代码:

def restore_presences(self, loop):
    async def func():
        db, c = self.connect()
        c.execute('SELECT Presenza FROM Teachers')
        presences = c.fetchall()
        for item in presences:
            c.execute('UPDATE Teachers SET Presenza = ?', ('no',))
            db.commit()
        db.close()

    threading.Thread(target=lambda loop: loop.run_until_complete(func()), args=(loop,)).start()


# THIS BLOCKS MY CODE
t = Timer(30, self.restore_presences, args=[asyncio.get_event_loop()])
t.start()
t.join()
# THIS BLOCKS MY CODE

async功能运行完美。

标签: pythonpython-asynciopython-multithreading

解决方案


推荐阅读