简体   繁体   English

Lambda function 将其变量值存储多长时间?

[英]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.我创建了一个 lambda 脚本只是为了了解 lambda 脚本将其变量值存储了多长时间。 Prior to this, my understanding was that it only stores until the function stops.在此之前,我的理解是它只存储到 function 停止。 But when I run the following script every 5 minutes (with the help of EventBridge), I got the following output:但是当我每 5 分钟运行一次以下脚本时(在 EventBridge 的帮助下),我得到了以下 output:

from datetime import datetime
current_time = datetime.now() 

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

Output (on 5 minutes interval) Output(每 5 分钟一班)

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.在我看来,我的 Lambda 脚本只会在 2-3 小时后而不是每 5 分钟重新运行一次。 Anyone knows why is that so?有谁知道为什么会这样? And how do I make it accurate per 5 mins?我如何让它每 5 分钟准确一次?

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 .lambda_handler中。 This makes current_time a local variable rather than global variable.这使得current_time成为局部变量而不是全局变量。 A global variable stores its value across multiple invocations.全局变量在多次调用中存储它的值。

See Operating Lambda: Performance optimization to learn about environment reuse.请参阅操作 Lambda:性能优化以了解环境重用。

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.在冷启动时,您的模块级初始化代码将运行(导致 current_time 被设置为`datetime.now())但是在热启动时,您的模块级初始化不运行,但是初始化的模块级值来自先前的调用仍然存在。

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.这是一个有用的功能,因为它允许 Lambda function 完成某种级别的缓存。但是,您不能 100% 依赖它,因为您的 function 不会总是热启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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