'AWS Lambda check for successful run in the last hour

I have a Lambda which retrieves JSON from an API, saves the contents of it in a file and stores the file in S3 bucket.

I've set up CloudWatch (EventBridge) to run the Lambda every 5 minutes, but I need to find a way to check if the API is called within the last hour. If it's called - Lambda shouldn't call it again. If it's not - Lambda should call it.

Tried to save the last run in the function itself, but every time it is invoked the variable is overwritten, so this doesn't work. Sample code below:

def f_main():
    current_time = int(time.time())
    last_run = 0

    def f1():
        global last_run
        last_run = int(time.time())
        print("f1 executed")

    if last_run + 3600 < current_time:
        f1()
    else:
        print("the current time is {}. The function was last executed at {}".format(current_time, last_run))


Solution 1:[1]

As @luj2302 suggested, you can check the timestamp of the latest stored response if you can predict its key. If not, or if you care about the response time of your check, use a DynamoDB table for such flags. I found that DynamoDB is much faster to store flags than S3

Note: Added this answer as I cannot add comments as a new contributor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A.Amayreh