Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用基于异步函数的threading.Timer_Python_Multithreading_Lambda_Python Asyncio - Fatal编程技术网

Python 使用基于异步函数的threading.Timer

Python 使用基于异步函数的threading.Timer,python,multithreading,lambda,python-asyncio,Python,Multithreading,Lambda,Python Asyncio,我正在用Python开发一个Discord机器人,它将YouTube上的音乐排成队列,我正在做一些事情,以便在播放器停止时自动将歌曲排成队列,虽然所有代码都工作得很好,但唯一的问题是我无法每15秒检查一次播放器是否正在播放 async def cmd_autoqueue(self,message, player,channel,author, permissions, leftover_args): print("autoq ran") if started ==

我正在用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:但是,异步lambda

另外,布尔值也被其他东西很好地管理,这是为了“如果”,在这里的问题

解决方案:

    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)

您可以稍后使用loop.call_,它将返回一个与asyncio兼容的处理程序来取消任务

你的班级: def初始化(自身): self.\u loop=asyncio.get\u event\u loop() self.\u check\u handler=None

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绑定参数