访问两个协程之间的公共共享变量

时间:2019-06-14 03:29:36

标签: python python-3.x python-asyncio coroutine google-cloud-pubsub

我正在使用GCP PubSub开发Python3.6。

  1. 我正在从PubSub回调订阅的主题。

  2. 收到回叫消息后,我将消息排队并进行ACK

  3. 我在init_apns_process()中处理了收到的消息

未来的问题:

如果我立即(正在做)确认回调,并且在processing(init_apns_process)发生异常时,我将从任一端丢失消息。

期望:

init_apns_process()完成之前不对ACK PubSub进行确认。

到目前为止,我的解决方案是

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之间是否可以基于其值共享标记?

0 个答案:

没有答案