'How long does Lambda function store its variable value?

I created a lambda script just to understand how long a lambda script stores its variable value. Prior to this, my understanding was that it only stores until the function stops. But when I run the following script every 5 minutes (with the help of EventBridge), I got the following output:

from datetime import datetime
current_time = datetime.now() 

def lambda_handler(event, context):   
   print(current_time)

Output (on 5 minutes interval)

06:16AM: 061649
06:21AM: 061649
06:26AM: 061649
06:31AM: 061649
06:36AM: 061649
...
08:39AM: 083934
08:44AM: 083934
08:49AM: 083934
08:54AM: 083934
08:59AM: 083934
...
10.41AM: 104149
10.46AM: 104149
10.51AM: 104149
10.56AM: 104149
...

Seems to me like my Lambda script only rerun itself after 2-3 hours instead of every 5 minutes. Anyone knows why is that so? And how do I make it accurate per 5 mins?



Solution 1:[1]

See Operating Lambda: Performance optimization to learn about environment reuse.

Upon a cold start, your module-level initialization code will be run (resulting in current_time being set to `datetime.now()) but upon a warm start, your module-level initialization is not run, however the initialized module-level values from the prior invocation remain.

This is a useful feature because it allows some level of caching to be done by the Lambda function. You can't rely on it 100%, however, because your function will not always be warm-started.

Solution 2:[2]

Found my answer! In order to refresh the time every invocation, I have to place the assignment i.e.

current_time = datetime.now()

within the lambda_handler. This makes current_time a local variable rather than global variable. A global variable stores its value across multiple invocations.

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 jarmod
Solution 2 fedonev