【问题标题】:Schedule lambda function once every day每天安排一次 lambda 函数
【发布时间】:2022-04-08 15:00:37
【问题描述】:

我有一个按预期工作的 cloudformation 模板。它安装了python lambda函数。

https://github.com/shantanuo/easyboto/blob/master/install_lambda.txt

但是我如何每天运行一次函数呢?我知道 yaml 代码看起来像这样......

  NotifierLambdaScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Name: 'notifier-scheduled-rule'
      Description: 'Triggers notifier lambda once per day'
      ScheduleExpression: cron(0 7 ? * * *)
      State: ENABLED

换句话说,如何在我的 cloudformation 模板中集成 cron 设置?

【问题讨论】:

  • 你可以在examples找到它。见Targets

标签: amazon-cloudformation


【解决方案1】:

我使用的一个例子:

  # Cronjobs
  ## Create your Lambda
  CronjobsFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: FUNCTION_NAME
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        S3Bucket: !Sub ${S3BucketName}
        S3Key: !Sub ${LambdasFileName}
      Runtime: nodejs8.10
      MemorySize: 512
      Timeout: 300

  ## Create schedule
  CronjobsScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Description: Scheduled Rule
      ScheduleExpression: cron(0 7 ? * * *)
      # ScheduleExpression: rate(1 day)
      State: ENABLED
      Targets:
        - Arn: !GetAtt CronjobsFunction.Arn
          Id: TargetFunctionV1

  ## Grant permission to Events trigger Lambda
  PermissionForEventsToInvokeCronjobsFunction:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref CronjobsFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt CronjobsScheduledRule.Arn

  ## Create Logs to check if events are working
  CronjobsFunctionLogsGroup:
    Type: AWS::Logs::LogGroup
    DependsOn: CronjobsFunction
    DeletionPolicy: Delete
    Properties:
      LogGroupName: !Join ['/', ['/aws/lambda', !Ref CronjobsFunction]]
      RetentionInDays: 14

您可以查看 Rate 和 Cron Expressions here

【讨论】:

    【解决方案2】:

    其他人可以为您提供一个没有无服务器的 Lambda 工作示例。但是,如果您将无服务器转换与 AWS Cloudformation(基本上是 SAM - 无服务器应用程序模型)一起使用,您可以非常轻松地安排您的 lambda。

    例如:

      ServerlessTestLambda:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: src
          Handler: test-env-var.handler
          Role: !GetAtt BasicLambdaRole.Arn
          Environment:
            Variables:
              Var1: "{{resolve:ssm:/test/ssmparam:3}}"
              Var2: "Whatever You want"
          Events:
            LambdaSchedule:
              Type: Schedule
              Properties:
                Schedule: rate(1 day)
    

    这个 lambda 每天都会自行触发。

    更多信息:https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2019-01-13
      相关资源
      最近更新 更多