简体   繁体   中英

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM