当计划基于费率时,是否有更优雅的方法来忽略初始事件回调

问题描述 投票:0回答:1

我有一个多步骤过程,可以在不同的时间间隔回调单个 Lambda。从纸面上看,这似乎非常干净,但是,我发现基于速率的计划事件会在启用后立即或不久后被调用,然后落入定义的速率间隔内。

如果创建的事件的时间表为“速率(5 分钟)”,它将在大约 1-2 分钟内回调指定的 lambda,然后遵循 5 分钟的回调周期。据我所知,这没有记录。我使用了一个令人讨厌的黑客,如下所示。是否有我忽略的神奇属性或者这就是设计?

在这里,我对消息进行了回调计数以忽略第一条消息。令人沮丧的是,对于 5 分钟计时器来说,初始回调似乎在 1 到 4 分钟之间,或者根本没有,这使得它有点不稳定。

def handle_and_skip_events_instant_start_callback(event):
    # simply increment a count per event and ingnore the first call back as it can be 
    # called anytime after the event was enabled or put such a 1 minute or 4 minutes for a 5 minute timer    
    if event["callBackCount"] == 0:
        # return false to ignore the event and place a new message with an incremented count
        event["callBackCount"] = event["callBackCount"] + 1 
        events_client.put_targets(Rule = event["ruleName"],
            Targets=[
            {
                'Id': "1", 
                'Arn': event["callbackFunctionArn"],
                'Input': json.dumps(event, default=str)
            }
            ]
        )  
        return True
    return False

def lambda_handler(event, context):
           
    if event.get('callbackMessageId', None) == None:
       start_replication_task(0, event, context)
       return

    # this is a callback from an event created for polling

    if handle_and_skip_events_instant_start_callback(event):
        #It is made so rate based scheduled events fire when they are
        # enabled or within ~1 minute of being enabled. This means a 5 minute timed event could fire 25 seconds
        # after created, afterwhich it would then ride on the schedule. Handle the awkward initial burst of the event here
        return     

    if event["messageType"] == "task":
        task_polling_callback_handler(event, context)
        return
    
    if event["messageType"] == "database":
        database_polling_callback_handler(event, context)
        return
    
    if event["messageType"] == "stoptask":
        stop_task_polling_callback_handler(event, context)
        return
    
    print("Error : Invalid callack message")      
    return 0   
aws-lambda amazon-cloudwatch aws-event-bridge
1个回答
1
投票

您使用的是 EventBridge 计划规则还是新的 EventBridge 计划程序服务 (https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduler.html)?

我建议您使用 EventBridge Scheduler 按计划调用目标 (https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html)。

© www.soinside.com 2019 - 2024. All rights reserved.