j3d
j3d

Reputation: 9724

How to schedule a lambda function to run every 30 minutes

I've a lambda with the following signature...

func handler(ctx context.Context, cwe events.CloudWatchEvent) error {

    ...
}

func main() {
    lambda.Start(handler)
}

... and I'm trying to configure it to run every 30 minutes:

  AuthGcFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/auth/gc
      Handler: gc
      Runtime: go1.x
      Tracing: Active
      Policies:
      - DynamoDBCrudPolicy:
        TableName: !Ref AuthInfoTable
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: cron(0/30 * * * ? *)
            Description: "Collects unconfirmed, expired auth entries"
            Enabled: true
      Environment:
        Variables:
          DYNAMODB_AUTH_INFO_TABLE: !Ref AuthInfoTable
          AUTH_EXPIRES_IN: !Ref AuthExpiresIn

When I try to deploy it (with sam), I always get the following error:

CREATE_FAILED             AWS::Events::Rule         AuthGcFunctionScheduled   Parameter
                                                    Event                     ScheduleExpression is  not valid. (Service:
                                                                              AmazonCloudWatchEvents;  Status Code: 400; Error
Code:
                                                                              ValidationException;
                                                                              Request ID: f32770c3-be
                                                                              cd-48a8-943f-f339103869
                                                                              3d; Proxy: null)

Reading the AWS documentation it seems my cron expression is correct... so I'm wondering whatever else might be wrong.

Upvotes: 1

Views: 5077

Answers (2)

nirvana124
nirvana124

Reputation: 1033

I created event bridge rule from below CDK code

new Rule(this, 'MyRule', {
    schedule: Schedule.cron({minute: '30'})
});

And cloudformation generated by this code is

Resources:
  MyRuleA44AB831:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0/30 * * * ? *)
      State: ENABLED

You can also use rate in schedule expression to run every 30 minutes.

Resources:
  MyRuleA44AB831:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: rate(30 minutes)
      State: ENABLED

Can you try this expression and check if this works for you.

Upvotes: 3

j3d
j3d

Reputation: 9724

In the end my original configuration worked... and frankly speaking I don't know what the problem was. I guess after many deploys-and-retries the server went stuck. After a couple of hours I was able to deploy successfully.

Upvotes: 1

Related Questions