python - 访问两个协程之间的公共共享变量
问题描述
我正在使用 GCP PubSub 开发 Python3.6。
我从 PubSub 收到订阅主题的回调。
收到回调消息后,我将消息排队并ACK
我在 init_apns_process() 中处理了收到的消息
未来的问题:
如果我立即确认回调(正在执行)并且processing(init_apns_process)
发生异常时,我将丢失来自任一端的消息。
期待:
在完成之前不要 ACK PubSub init_apns_process()
。
到目前为止我的解决方案:
apns_msg_queue = queue.Queue()
start_time = 0
async def init_apns_process(message):
logging.info("Process Msg: {0}".format(message))
await send_apns_notification(token)
async def send_apns_notification(device_token):
global start_time
apns = None
apns = mi_apns_dev
apns_payload = {"alert": "hello world 121", "serial": 21, "sound": "mov.mp3",
"mutable-content": "1", "category": "done", "id": -9999}
if apns is not None:
request = NotificationRequest(
device_token=device_token,
message={"aps": apns_payload}
)
ret = await apns.send_notification(request)
if not ret.is_successful:
logger.error(
f"Failed to send APNS notification ID:")
else:
logging.info(f"Successfully sent APNS notification"
f" Time Taken in processing: {time.time() - start_time}")
#update shared FLAG
def callback_value(message):
apns_msg_queue.put(message)
# return based on value of shared FLAG
return True
if __name__ == '__main__':
logger.setup()
mi_apns_dev = APNs('apns.pem', use_sandbox=False)
loop = asyncio.get_event_loop()
subscriber = sub.PubSubSubscriber()
subscriber.subscribe(subscription_name, callback_value, auto_ack_on_received=False)
while True:
if apns_msg_queue.qsize() > 0:
msg = apns_msg_queue.get()
if msg is None:
break
loop.run_until_complete(init_apns_process(msg))
time.sleep(5)
可以在上述两个任务和基于其值的 ACK PubSub 之间有一些共享标志吗?
解决方案
推荐阅读
- dart - 如何将图像转换为 base64 和 base64 为图像?我这样做的方式行不通
- variables - c# 7.0 tuple 用作自定义类型
- java - 运行 Spring Boot JAR 应用程序不会使用浏览器打开 URL(https://localhost:8080/)
- javascript - 想要通过单击将标签内容保存在 cookie 上
- javascript - 如何拦截自动提交表单?
- javascript - 如果使用javascript动态添加按钮,如何知道单击了哪个按钮?
- python - 如何从 docx 文件中提取文本并存储在文本文件中
- go - 设计 Go 程序以避免循环依赖
- python - 数据框到 html 格式化程序(使用 Flask)将应用于所有列
- logstash - 如何编写自定义的 grok 模式?