python 停止异步任务,该任务是在类的函数内启动的

jum4pzuy  于 2023-01-08  发布在  Python
关注(0)|答案(1)|浏览(114)

我试图取消一个特定的asyncio任务,这个任务是在一个类的函数中启动的。但是它不起作用。这个任务又重新启动了.... a.谢谢你的启发!:)

def button_stop_command(): 

        t1.cancel()

        #check which tasks are running
        tasks = asyncio.all_tasks()
        for task in tasks:
          print(f'> {task.get_name()}, {task.get_coro()}')

class ZMQHandler():
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        url= 'tcp://192.168.0.91:28332'
        channel= 'sequence'   
        self.ctx = zmq.asyncio.Context.instance()   
        self.sock = self.ctx.socket(zmq.SUB)
        self.sock.connect(url)
        self.sock.setsockopt(zmq.SUBSCRIBE, channel.encode())
        print("Open ZMQ socket on", ZMQ_URL)

    async def handle(self) :
        [..code...]
        asyncio.ensure_future(self.handle())

    def start(self): 
        global t1    
        self.loop.add_signal_handler(signal.SIGINT, self.stop)       
        t1=self.loop.create_task(self.handle())
        self.loop.run_forever()
 

       
async def tk_main(root):
    while True:
        root.update()
        await asyncio.sleep(0.05)

tkmain = asyncio.ensure_future(tk_main(root))   
daemon = ZMQHandler()
daemon.start()

我想取消特定任务

guicsvcw

guicsvcw1#

每次我发布一些东西,我得到一个新的想法,然后问题得到解决。我的想法是:

def button_stop_command(): 

        t1.cancel()

        #check which tasks are running
        tasks = asyncio.all_tasks()
        for task in tasks:
          print(f'> {task.get_name()}, {task.get_coro()}')

class ZMQHandler():
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        url= 'tcp://192.168.0.91:28332'
        channel= 'sequence'   
        self.ctx = zmq.asyncio.Context.instance()   
        self.sock = self.ctx.socket(zmq.SUB)
        self.sock.connect(url)
        self.sock.setsockopt(zmq.SUBSCRIBE, channel.encode())
        print("Open ZMQ socket on", ZMQ_URL)

    async def handle(self) :
        global t1 
        [..code...]
        t1= asyncio.ensure_future(self.handle())

    def start(self): 
           
        self.loop.add_signal_handler(signal.SIGINT, self.stop)       
        self.loop.create_task(self.handle())
        self.loop.run_forever()
 

       
async def tk_main(root):
    while True:
        root.update()
        await asyncio.sleep(0.05)

tkmain = asyncio.ensure_future(tk_main(root))   
daemon = ZMQHandler()
daemon.start()

相关问题