gpt4 book ai didi

amazon-web-services - 是否可以使用一个 AWS Lambda 函数附加多个计划/cron 事件?

转载 作者:行者123 更新时间:2023-12-05 06:07:06 25 4
gpt4 key购买 nike

目前,我的 lambda 函数在附加一个计划事件的情况下成功运行。我的 template.yaml 中的相关摘录:

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.App::handleRequest
Runtime: java11
MemorySize: 512
Environment:
Variables:
PARAM1: VALUE
Events:
CronHourlyEvent: # This already works
Type: Schedule
Properties:
Description: Send John Doe
Enabled: True
Schedule: "cron(0 0/1 * * ? *)"
Input: !Sub '{"name": "John Doe"}'

Lambda 在这里每隔一小时触发一次,并且工作正常。

现在我想添加另一个计划事件,每天中午 12 点触发一次相同的 lambda。一种方法是创建一个单独的 lambda 并将每日计划事件附加到它,但我不想为此创建一个新的 lambda。我希望我是否可以将两个计划事件附加到同一个 lambda。

我在网上找不到任何将多个计划事件附加到 lambda 的示例,但我认为需要在 template.yaml 文件中添加以下内容:

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.App::handleRequest
Runtime: java11
MemorySize: 512
Environment:
Variables:
PARAM1: VALUE
Events:
CronHourlyEvent: # this was already present
Type: Schedule
Properties:
Description: Send John Doe
Enabled: True
Schedule: "cron(0 0/1 * * ? *)"
Input: !Sub '{"name": "John Doe"}'
CronDailyEvent: # added this
Type: Schedule
Properties:
Description: Send Jane Doe
Enabled: True
Schedule: "cron(0 12 1/1 * ? *)"
Input: !Sub '{"name": "Jane Doe"}'

想在本地测试一下,于是下载并配置了sam-sdk。但我认为这不支持在本地运行 cron 作业。我能够手动触发事件,但找不到任何根据提供的 cron 表达式自动运行计划作业的规定。

所以我想知道:

  1. 我们是否可以将 2 个或更多计划/cron 类型的事件附加到 AWS lambda 函数?
  2. 如果是,我所做的代码更改是否正确?

这将直接投入生产,我似乎无法找到在本地测试它的方法。

最佳答案

我正在使用类似于以下的配置,它完美地工作并满足我的需求。

Resources:
SayHelloWorldRule:
Type: AWS::Events::Rule
Properties:
Description: The rule for greeting the world
Name: ${self:provider.stage}-say-hello-world-rule
ScheduleExpression: 'cron(0 7 * * ? *)'
State: ENABLED
Targets:
-
Arn:
!Join [ ':', [ 'arn:aws:lambda', Ref: AWS::Region, Ref: AWS::AccountId, 'function', 'HelloWorldFunction' ] ]
Id: "GreetTheWorldDaily"
Input: '{"user": "Sudo user", "message": "Hello world!!!"}'

SayGoodbyeWorldRule:
Type: AWS::Events::Rule
Properties:
Description: "It's time to say goodbye"
Name: ${self:provider.stage}-say-goodbye-rule
ScheduleExpression: 'cron(30 22 * * ? *)'
State: ENABLED
Targets:
-
Arn:
!Join [ ':', [ 'arn:aws:lambda', Ref: AWS::Region, Ref: AWS::AccountId, 'function', 'HelloWorldFunction' ] ]
Id: "SayGoodbyeDaily"
Input: '{"user": "Sudo user", "message": "Auf Wiedersehen!!!"}'

PermissionForEventsToInvokeHelloWorldLambda:
Type: AWS::Lambda::Permission
Properties:
FunctionName: HelloWorldFunction
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"

关于amazon-web-services - 是否可以使用一个 AWS Lambda 函数附加多个计划/cron 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65592019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com