异步 Stopping/pausing

Asyncio Stopping/pausing

我正在努力实现,一旦满足 print_handle(data) 中的条件,我想暂停当前异步,用我的 query2 创建一个新的异步请求,关闭该请求,然后继续与第一个。

from python_graphql_client import GraphqlClient
import asyncio
import os
import requests

headers={'Authorization': "2bTxxxxxxxxxxxxxxxxxxx"}

def print_handle(data):
    print(data["data"]["liveMeasurement"]["timestamp"]+" "+str(data["data"]["liveMeasurement"]["power"]))
    tall = (data["data"]["liveMeasurement"]["power"])
    if tall > 100:
        print("OK")
        #pause the current async thread, create a new one with the 
        #query2, close that one, and continue with the first. 

client = GraphqlClient(endpoint="wss://api.tibber.com/v1-beta/gql/subscriptions")

query = """
subscription{
  liveMeasurement(homeId:"xxxxxxxxxxxxxxxa"){
    timestamp
    power
  }
}
"""

query2 = """
mutation{
  sendPushNotification(input: {
    title: "Varsel! Høy belastning",
    message: "Du bruker nå høyere effekt enn 5 kw, pass på forbruket",
    screenToOpen: CONSUMPTION
  }){
    successful
    pushedToNumberOfDevices
  }
}
"""

async def main():
    await client.subscribe(query=query, headers={'Authorization': "2xxxxxxxxxxxxxxxx"}, handle=print_handle)
    
asyncio.run(main())

我认为您混淆了多线程和异步编程。你不想暂停你的线程,因为那意味着你会暂停你的整个程序。 我从您的代码中得知,您希望在满足某些条件(取决于您的数据)后发送推送消息。我不认为你需要为此暂停任何事情。它可以像安排发送该消息的任务一样简单。你可以选择这样的东西:

from python_graphql_client import GraphqlClient
import asyncio
import os
import requests

headers={'Authorization': "2bTxxxxxxxxxxxxxxxxxxx"}

def print_handle(data):
    print(data["data"]["liveMeasurement"]["timestamp"]+" "+str(data["data"]["liveMeasurement"]["power"]))
    tall = (data["data"]["liveMeasurement"]["power"])
    if tall > 100:
        print("OK")
        # schedule async task from sync code
        asyncio.create_task(send_push_notification(data))

client = GraphqlClient(endpoint="wss://api.tibber.com/v1-beta/gql/subscriptions")

query = """
subscription{
  liveMeasurement(homeId:"xxxxxxxxxxxxxxxa"){
    timestamp
    power
  }
}
"""

query2 = """
mutation{
  sendPushNotification(input: {
    title: "Varsel! Høy belastning",
    message: "Du bruker nå høyere effekt enn 5 kw, pass på forbruket",
    screenToOpen: CONSUMPTION
  }){
    successful
    pushedToNumberOfDevices
  }
}
"""

async def send_push_notification(data):
    #maybe update your query with the received data here
    await client.execute_async(query=query2) #pass whatever other params you need

async def main():
    await client.subscribe(query=query, headers={'Authorization': "2xxxxxxxxxxxxxxxx"}, handle=print_handle)
    
asyncio.run(main())