Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule lambda function once every day

I have a cloudformation template that works as expected. It install python lambda function.

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

But how do I run the function once every day? I know the yaml code will look something like this...

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

In other words, how do I integrate cron setting in my cloudformation template?

like image 882
shantanuo Avatar asked Jul 14 '26 13:07

shantanuo


1 Answers

An example of CloudFormation template I use:

  # 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

You can check about Rate and Cron Expressions here.

But, if you want to run the above job once a day at 07:00 AM (UTC), then the expression should probably be: cron(0 7 * * ? *)

like image 63
Pedro Arantes Avatar answered Jul 21 '26 09:07

Pedro Arantes