首页 > 解决方案 > 如何在 00、10、20、30、40、50 每 10 分钟运行一次无服务器 lambda 函数

问题描述

我有一个使用用 nodejs 编写的无服务器框架作为 lambda 部署在 AWS 上的函数。我已经安排了一个活动,让这个函数/cron 作业每 10 分钟运行一次。

我希望这个 cron 作业每 10 分钟运行一次。我假设它会在每小时 00,10,20,30,40,50 分钟标记处运行。

然而事实并非如此,它似乎从部署时每 10 分钟运行一次,例如,如果我在 10:05 部署应用程序,它将在 10:15、10:25、10 运行:35、10:45、10:55、11:05。当然是每 10 分钟一次,但这并不是我想要的。

有没有办法让我的 lambda 函数在 00、10、20、30、40、50 时每 10 分钟执行一次?

serverless.ts / serverless.yml

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

谢谢

标签: amazon-web-servicesaws-lambdacronserverless-frameworkserverless

解决方案


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


推荐阅读