Kay
Kay

Reputation: 19660

How to run a severless lambda function every 10 minutes at 00, 10, 20, 30, 40, 50

I have a function that is deployed on AWS as a lambda using a serverless framework written in nodejs. I have scheduled an event to have this function/cron job run every 10 minutes.

I want this cron job to run every 10 minutes. I assume that it would run at 00,10,20,30,40,50 min mark every hour.

However that's not the case, it seems like it is running every 10 minutes from the time at which it was deployed, for example, if I deployed the app at 10:05, it will run at 10:15, 10:25, 10:35, 10:45, 10:55, 11:05. Sure it's every 10 minutes but it's not quite what I'm looking for.

is there a way to get my lambda function to execute every 10 minutes at 00, 10, 20, 30, 40, 50?

serverless.ts / serverless.yml

functions: {
    main: {
        handler: "handler.main",
        events: [{
            schedule: "rate(10 minutes)",
        }],
    },
},

thanks

Upvotes: 2

Views: 5226

Answers (1)

Daniel Hornik
Daniel Hornik

Reputation: 2521

You need to involve Cloudwatch Rules into that.

There is good tutorial from AWS here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html

Basically there are required actions:

  1. Create CloudWatch Event rule
  2. Add lambda:InvokeFunction permission with principal events.amazonaws.com to your lambda
  3. Put target to your event rule. Target is your lamba will be started.

If you want to run this with the Serverless framework, you can use schedule provider.

functions:
  crawl:
    handler: crawl
    events:
      - schedule: rate(2 hours)
      - schedule: cron(0 12 * * ? *)

https://www.serverless.com/framework/docs/providers/aws/events/schedule/

Update: How to run a specific times

If you want to run your tasks at specific time, you can use this expression:

cron(0,10,20,30,40,50 * * * ? *)

More info about Schedule expression is here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions

Upvotes: 3

Related Questions