我正在使用Python制作Discord机器人,它将来自YouTube的音乐排队,当播放器停止时我正在处理某些事情以使歌曲自动化,而所有代码都完美无缺,这是唯一的问题是我无法每15秒检查一下玩家是否在玩
async def cmd_autoqueue(self,message, player,channel,author, permissions, leftover_args):
print("autoq ran")
if started == True:
if player.is_stopped:
await self.cmd_autoqadd(player, channel, author, permissions,leftover_args,song_url=last_url)
threading.Timer(15.0,await self.cmd_autoqueue(message, player,channel,author, permissions, leftover_args)).start()
我确实意识到了
threading.Timer(15.0,await self.cmd_autoqueue(message, player,channel,author, permissions, leftover_args)).start()
调用该函数,如果我想将它作为稍后调用的东西传递,我会使用lambda:但是,async lambda?
也开始布尔由其他东西很好地管理它为了' if'在这个问题中
解决方案:
async def cmd_autoqueue(self,message, player,channel,author, permissions, leftover_args):
global started
print("loop")
if started == True:
await asyncio.sleep(15)
if player.is_stopped:
await self.cmd_autoqadd(player, channel, author, permissions,leftover_args,song_url=last_url)
await self.cmd_autoqueue(message, player,channel,author, permissions, leftover_args)
答案 0 :(得分:0)
你可以使用loop.call_later,它会返回一个与asyncio兼容的处理程序来取消任务。
类YourClass: def init (个体经营): self._loop = asyncio.get_event_loop() self._check_handler =无
def schedule_check(self):
self._check_handler = loop.call_later(
15 * 60, # Every 15 minutes
self._loop.create_task, self._periodic_check())
def stop_checking(self):
self._check_handler.cancel()
async def start_player(self):
await do something()
if not check_handler:
schedule_check()
async def stop_player(self):
await do something()
self.stop_checking()
async def _periodic_check(self):
await do_something()
self._schedule_check()
要将一个函数(需要一些参数)作为参数传递给另一个函数,不允许传递参数,可以使用functools.partial绑定参数。