Search code examples
amazon-web-servicesaws-lambdaaws-cdkaws-event-bridge

Schedule AWS lambda in a interval with immediately trigger


To run lambda in an interval, I could use EventBridge rule: https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html

For example, if I set the rule to 7 days, the lambda will execute at 7 days after the lambda is created.

What if I need to run this lambda immediately after its creation and also run this lambda in an interval?

How can I do this programmatically or in CDK?


Solution

  • Note: This solution only works for those who use AWS CodeBuild to deploy their Lambdas.

    In this sample project (https://github.com/dashmug/us-covid-stats) I did a while back, I configured the Lambda to also have another trigger based on CodeBuild's "Build Succeeded" event.

    In https://github.com/dashmug/us-covid-stats/blob/main/backend/serverless.yml#L71,

    RefreshDataFromSources:
        handler: us_covid_stats/etl/handler.refresh_data_from_sources
        events:
          - schedule:
              enabled: false
              rate: rate(1 day)
          - cloudwatchEvent:
              enabled: false
              event:
                source:
                  - aws.codebuild
                detail-type:
                  - CodeBuild Build State Change
                detail:
                  build-status:
                    - SUCCEEDED
                  project-name:
                    - us-covid-stats-deployment-backend
    

    you'll see that the Lambda is normally triggered once daily. But also on top of the daily schedule, it is triggered when the deployment succeeds.