简体   繁体   English

AWS Lambda 计划任务

[英]AWS Lambda Scheduled Tasks

Amazon announced AWS Lambda ( http://aws.amazon.com/lambda/ ).亚马逊宣布 AWS Lambda ( http://aws.amazon.com/lambda/ )。

The product description includes:产品说明包括:

Scheduled Tasks计划任务

AWS Lambda functions can be triggered by external event timers, so functions can be run during regularly scheduled maintenance times or non-peak hours. AWS Lambda 函数可以由外部事件计时器触发,因此函数可以在定期维护时间或非高峰时段运行。 For example, you can trigger an AWS Lambda function to perform nightly archive cleanups during non-busy hours.例如,您可以触发 AWS Lambda function 在非繁忙时间执行夜间存档清理。

When I read this, I understood I could finally have a way to consistently do "cron-like" tasks.当我读到这篇文章时,我明白我终于可以有一种方法来始终如一地执行“类似 cron 的”任务。 I want to run a specific query everyday at 5PM let's say.我想每天下午 5 点运行一个特定的查询。

However I do not find this anywhere in the documentation.但是我在文档中的任何地方都找不到这个。 They only mention triggers on programatical events, or events from other AWS services.他们只提到程序事件或来自其他 AWS 服务的事件的触发器。

Did I misunderstand?我误会了吗? Or can someone point me to the documentation?或者有人可以指出我的文档吗?

Native Support for Scheduled Events added October 8, 2015: 2015 年 10 月 8 日添加的对预定事件的原生支持:

As announced in this AWS blog post , scheduling is now supported as an event source type (also called triggers) called " CloudWatch Events - Schedule ", and can be expressed as a rate or a cron expression.正如这篇AWS 博客文章 中所宣布,现在支持调度作为称为“ CloudWatch Events - Schedule ”的事件源类型(也称为触发器),并且可以表示为速率或 cron 表达式。

Add Scheduled Event to a new lambda将预定事件添加到新的 lambda

Navigate to the 'Configure triggers' step of creation, and specify the 'CloudWatch Event - Schedule' trigger.导航到创建的“配置触发器”步骤,并指定“CloudWatch 事件 - 计划”触发器。 Example configuration below:下面的示例配置:

显示用于在 UTC 下午 5 点创建计划事件的配置的图像。

Add Scheduled Event to an existing lambda将预定事件添加到现有的 lambda

Navigate to the 'Triggers' tab of your lambda, select 'Add Trigger', and specify the 'CloudWatch Event - Schedule' trigger.导航到 lambda 的“触发器”选项卡,选择“添加触发器”,然后指定“CloudWatch 事件 - 计划”触发器。 Example screenshot where I have an existing lambda with an SNS trigger:我有一个带有 SNS 触发器的现有 lambda 的示例屏幕截图:

显示如何从 Lambda 控制台导航以添加触发器 UI 的图像。

Once loaded, the UI to configure this trigger is identical to the screenshot in the above "Add Scheduled Event to a new lambda" section above.加载后,用于配置此触发器的 UI 与上面“将计划事件添加到新 lambda”部分中的屏幕截图相同。

Discussion讨论

For your example case, you'll want to use cron() instead of rate() .对于您的示例,您需要使用cron()而不是rate() Cron expressions in lambda require all fields and are expressed in UTC. lambda 中的 Cron 表达式需要所有字段,并以 UTC 表示。 So to run a function every day at 5pm (UTC), use the following cron expression:因此,要每天在下午 5 点 (UTC) 运行一个函数,请使用以下 cron 表达式:

cron(0 17 * * ? *)

Further Resources更多资源

Notes笔记

  • The name of this event type has changed from "Scheduled Event" to "CloudWatch Events - Schedule" since this feature was first released.自此功能首次发布以来,此事件类型的名称已从“计划事件”更改为“CloudWatch 事件 - 计划”。
  • Prior to the release of this feature, the recommended solution to this issue (per "Getting Started with AWS Lambda" at 42min 50secs ) was to use SWF to create a timer , or to create a timer with an external application.在此功能发布之前,此问题的推荐解决方案(根据“AWS Lambda 入门”在 42 分 50 秒)是使用 SWF 创建计时器,或使用外部应用程序创建计时器。
  • The Lambda UI has been overhauled since the scheduled event blog post came out, and the screenshots within are no longer exact.自预定事件博客文章发布以来,Lambda UI 已经过大修,其中的屏幕截图不再准确。 See my updated screenshots above from 3/10/2017 for latest revisions.有关最新修订,请参阅我在 2017 年 3 月 10 日更新的屏幕截图。

Since the time of this post, there seems to have risen another solution: Schedule Recurring AWS Lambda Invocations With The Unreliable Town Clock (UTC) in which the author proposes subscribing to the SNS topic Unreliable Town Clock .自这篇文章发布以来,似乎已经出现了另一种解决方案:使用不可靠的城镇时钟 (UTC) 安排重复的 AWS Lambda 调用,其中作者建议订阅 SNS 主题不可靠的城镇时钟 I've used neither SWF nor SNS, but it seems to me that the SNS solution is simpler.我既没有使用过 SWF,也没有使用过 SNS,但在我看来,SNS 解决方案更简单。 Here's an excerpt from the article这是文章的摘录

Unreliable Town Clock (UTC)不可靠的城市时钟 (UTC)

The Unreliable Town Clock (UTC) is a new, free, public SNS Topic (Amazon Simple Notification Service) that broadcasts a “chime” message every quarter hour to all subscribers. Unreliable Town Clock (UTC) 是一个新的免费公共 SNS 主题(亚马逊简单通知服务),每四分之一小时向所有订阅者广播一条“钟声”消息。 It can send the chimes to AWS Lambda functions, SQS queues, and email addresses.它可以将提示音发送到 AWS Lambda 函数、SQS 队列和电子邮件地址。

You can use the chime attributes to run your code every fifteen minutes, or only run your code once an hour (eg, when minute == "00") or once a day (eg, when hour == "00" and minute == "00") or any other series of intervals.您可以使用 chime 属性每 15 分钟运行一次代码,或者仅每小时运行一次代码(例如,当 minute == "00" 时)或每天一次(例如,当 hour == "00" 和 minute = = "00") 或任何其他系列的间隔。

You can even subscribe a function you only want to run only once at a specific time in the future: Have the function ignore all invocations until it's after the time it wants.你甚至可以订阅一个你只想在未来特定时间运行一次的函数:让函数忽略所有调用,直到它想要的时间之后。 When it is time, it can perform its job, then unsubscribe itself from the SNS Topic.时间到了,它可以执行它的工作,然后从 SNS 主题中取消订阅。

Connecting your code to the Unreliable Town Clock is fast and easy.将您的代码连接到 Unreliable Town Clock 既快速又简单。 No application process or account creation is required无需申请流程或创建帐户

NEW SOLUTION: Lambda Scheduled Jobs新解决方案:Lambda 计划作业

Werner Vogel has announced tonight (10/08) at re:Invent that AWS Lambda now has it's own scheduler. Werner Vogel 今晚 (10/08) 在 re:Invent 上宣布 AWS Lambda 现在拥有自己的调度程序。

Se the AWS Lambda release note on 2015-10-08 :请参阅2015 年 10 月 8 日AWS Lambda 发行说明

You can also set up AWS Lambda to invoke your code on a regular, scheduled basis using the AWS Lambda console.您还可以设置 AWS Lambda 以使用 AWS Lambda 控制台定期、按计划调用您的代码。 You can specify a fixed rate (number of hours, days, or weeks) or you can specify a cron expression.您可以指定固定比率(小时数、天数或周数),也可以指定 cron 表达式。 For an example, see Walkthrough 5: Using Lambda Functions to Process Scheduled Events (Python) .有关示例,请参阅演练 5:使用 Lambda 函数处理计划事件 (Python)


OLD SOLUTION: Scheduling with AWS Data Pipeline旧解决方案:使用 AWS Data Pipeline 进行调度

You can use AWS Data Pipeline to schedule a task with a given period.您可以使用 AWS Data Pipeline 在给定时间段内安排任务。 The action can be any command when you configure your Pipeline with the ShellCommandActivity .当您使用ShellCommandActivity配置管道时,该操作可以是任何命令。

You can for example run an AWS CLI command to:例如,您可以运行 AWS CLI 命令来:

  • Put a message to SQS向 SQS 发送消息
  • or directly invoke a Lambda function (see invoke )或直接调用 Lambda 函数(请参阅invoke

You can easily create the AWS Data Pipeline scheduled task directly within AWS console (eg with an AWS CLI command) :您可以直接在 AWS 控制台中轻松创建 AWS Data Pipeline 计划任务(例如,使用 AWS CLI 命令):

在此处输入图片说明

You can also use the API to define your scheduling:您还可以使用 API 来定义您的日程安排:

{
 "pipelineId": "df-0937003356ZJEXAMPLE",
 "pipelineObjects": [
    {
      "id": "Schedule",
      "name": "Schedule",
      "fields": [
        { "key": "startDateTime", "stringValue": "2012-12-12T00:00:00" }, 
        { "key": "type", "stringValue": "Schedule" }, 
        { "key": "period", "stringValue": "1 hour" }, 
        { "key": "endDateTime", "stringValue": "2012-12-21T18:00:00"  }
       ]
     }, {
      "id": "DoSomething",
      "name": "DoSomething",
      "fields": [
        { "key": "type", "stringValue": "ShellCommandActivity" },
        { "key": "command", "stringValue": "echo hello" },
        { "key": "schedule", "refValue": "Schedule" }
      ]
    }
  ]
}

Limits : Minimum scheduling interval is 15 minutes. 限制:最小调度间隔为 15 分钟。
Pricing : About $1.00 per month.定价:每月约 1.00 美元。

Here is how I do it:这是我如何做到的:

Now you have a timer with approximately 15 minutes resolution.现在您有一个分辨率约为 15 分钟的计时器。

Then other Lambda functions are subscribed to SNS Topic and called every 15 minutes.然后其他 Lambda 函数订阅 SNS 主题并每 15 分钟调用一次。

Since it is now easily possible to trigger lambda functions over HTTP (eg using GET or curl) a simple solution is to use a managed CRON like easycron: https://www.easycron.com/ to trigger your lambda function into running.由于现在很容易通过 HTTP 触发 lambda 函数(例如使用 GET 或 curl),一个简单的解决方案是使用像 easycron 这样的托管 CRON: https ://www.easycron.com/ 来触发您的 lambda 函数运行。

We had the same problem and ended up running a cron service on Google App Engine in python since this allowed for more flexibility and complexity in the CRON job itself.我们遇到了同样的问题,最终在 Python 中的 Google App Engine 上运行了一个 cron 服务,因为这允许 CRON 作业本身具有更大的灵活性和复杂性。

In the Function page, Add trigger, you can add a CloudWatch Events, and make it as a schedule type在 Function 页面的 Add trigger 中,您可以添加 CloudWatch Events,并将其设为计划类型

在此处输入图片说明

AWS Recently(10-Nov-2022) launched a new service called EventBridge Scheduler or you can choose EventBridge Rules for this as well. AWS 最近(2022 年 11 月 10 日)推出了一项名为EventBridge Scheduler的新服务,您也可以为此选择EventBridge 规则 As per your example here I'm going to trigger an event every day at 5.00 AM As you can see it shows us the next 10 trigger dates and times as well, this will really help us to manually check our cron before doing anything.根据您在此处的示例,我将在每天凌晨 5 点触发一个事件 正如您所看到的,它还向我们显示了接下来的 10 个触发日期和时间,这将真正帮助我们在执行任何操作之前手动检查我们的 cron。

Please note, if you want to start this schedule on a specific date and time, please choose EventBridge Scheduler for that.请注意,如果您想在特定日期和时间开始此计划,请为此选择EventBridge 计划程序 It has a Timeframe option.它有一个时间范围选项。 If you want to know more information about Timeframe please have look at this answer .如果您想了解有关Timeframe的更多信息,请查看此答案

在此处输入图像描述

In the target section, you can select 35 AWS Lambda function options.在目标部分,您可以选择 select 35 AWS Lambda function 选项。

在此处输入图像描述

Hope this will help you.希望这会帮助你。

You could schedule it with cloudWatch events too.您也可以使用 cloudWatch 事件来安排它。 Create rule -> attach target (lambda) and set up cron/rate wise schedule on your rule.创建规则 -> 附加目标 (lambda) 并在您的规则上设置 cron/rate 明智的计划。

The web-console way is pretty straightforward.网络控制台方式非常简单。 Just create a CloudWatch rule for the lambda and add it in the lambda's Triggers tab.只需为 lambda 创建CloudWatch规则并将其添加到 lambda 的Triggers选项卡中。

For those who needs to automate that with aws cli , we can对于那些需要使用aws cli自动化的人,我们可以

  1. create the function,创建函数,
  2. create the rule,创建规则,
  3. grant the permission,授予许可,
  4. link rule and function链接规则和功能

Create function创建函数

aws lambda create-function --function-name ${FUNCTION-NAME} \
--runtime java8 \
--role 'arn:aws:iam::${Account}:role/${ROLE}' \
--handler org.yourCompany.LambdaApp \
--code '{"S3Bucket":"yourBucket", "S3Key": "RC/yourapp.jar"}' \
--description 'check hive connection' \
--timeout 180 \
--memory-size 384 \
--publish \
--vpc-config '{"SubnetIds": ["subnet-1d2e3435", "subnet-0df4547a"], "SecurityGroupIds": ["sg-cb17b1ae", "sg-0e7ae277"]}' \
--environment Variables={springEnv=dev}

Create rules创建规则

## create
aws events put-rule --name ${ruleName} \
--schedule-expression 'rate(5 minutes)' \
--state ENABLED \
--description 'check hive connection'

# grant permission to the Rule to allow it to trigger the function
aws lambda add-permission --function-name ${functionName} \
--statement-id 123 \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-east-1:acc:rule/${ruleName}

# link rule and function
aws events put-targets --rule ${ruleName} \
--targets '[{"Id":"1", "Arn":"arn:aws:lambda:us-east-1:acc:function:RC-checkhive"}]'

simple way to run your query in lambda for particular time interval is to set rule for your lambda function.在特定时间间隔内在 lambda 中运行查询的简单方法是为 lambda 函数设置规则。 for that after creating lambda function go to cloudwatch>>rules>>schedule.为此,在创建 lambda 函数后,转到 cloudwatch>>rules>>schedule。 and define cron expression and in the target section select lambda function which you want to trigger.并定义 cron 表达式并在目标部分中选择要触发的 lambda 函数。

Run as cron in AWS在 AWS 中作为 cron 运行

An example to setup cloudwatch schedule event trigger for you lambda using cloudformation.使用 cloudformation 为您的 lambda 设置 cloudwatch 计划事件触发器的示例。


  LambdaSchedule:
    Type: "AWS::Events::Rule"
    Properties:
      Description: A schedule for the Lambda function..
      ScheduleExpression: rate(5 minutes)
      State: ENABLED
      Targets:
        - Arn: !Sub ${LambdaFunction.Arn}
          Id: LambdaSchedule

  LambdaSchedulePermission:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: 'lambda:InvokeFunction'
      FunctionName: !Sub ${LambdaFunction.Arn}
      Principal: 'events.amazonaws.com'
      SourceArn: !Sub ${LambdaSchedule.Arn}

  LambdaFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Description: Scheduled lambda to run every 5 minutes
      CodeUri: ./build/package.zip
      Handler: index.lambda_handler
      MemorySize: 128
      Runtime: python3.6

While creating the lambda function create trigger "CloudWatch Events - Schedule"在创建 lambda 函数时创建触发器“CloudWatch Events - Schedule”

Now you can either use AWS presets in schedule expression like rate = 15 min or you can use a cron expression.现在,您可以在计划表达式中使用 AWS 预设,例如 rate = 15 min,也可以使用 cron 表达式。

在此处输入图片说明

For your requirement the Cron Schedule is "0 0 17 1/1 * ? *"根据您的要求,Cron 计划是“0 0 17 1/1 * ? *”

Posted - 27 June 2021发布日期 - 2021 年 6 月 27 日

You can schedule AWS Lambda functions using Amazon EventBridge Here I am using AWS Management Console您可以使用Amazon EventBridge安排 AWS Lambda 函数这里我使用的是 AWS 管理控制台

  1. Select your Lambda function and in configuration select "Triggers"选择您的 Lambda 函数并在配置中选择“触发器” 在此处输入图片说明

  2. Select EventBridge(CloudWatch Events) - Basically this is the latest version of one of the popular answers(using CloudWatch triggers).选择EventBridge(CloudWatch Events) - 基本上这是流行答案之一的最新版本(使用 CloudWatch 触发器)。 在此处输入图片说明

  3. Create a new rule - Add details.创建新规则- 添加详细信息。 My lambda will be triggered at 4pm UTC everday我的 lambda 将在UTC每天下午 4 点触发在此处输入图片说明 . .

Here's an example of deploying up a Scheduled Lambda to run every 10 minutes using Serverless.这是一个使用无服务器部署计划的 Lambda 以每 10 分钟运行一次的示例。 The function handler is located at src/scheduled/index.handler and the rate is specified in the Lambda's settings. function 处理程序位于 src/scheduled/index.handler 并且速率在 Lambda 的设置中指定。 AWS uses EventBridge now to control when the Lambda should be invoked. AWS 现在使用 EventBridge 来控制何时调用 Lambda。 That is all setup automatically for you when using Serverless.这是使用无服务器时自动为您设置的所有内容。 You can see the setup in the AWS console by viewing the Lambda or by looking at the "default" EventBridge in the EventBridge section.您可以通过查看 Lambda 或查看 EventBridge 部分中的“默认”EventBridge 在 AWS 控制台中查看设置。

https://carova.io/snippets/serverless-aws-lambdafunction-scheduled-cronjob https://carova.io/snippets/serverless-aws-lambdafunction-scheduled-cronjob

EventsBridge (CloudWatch) Solution: EventsBridge (CloudWatch) 解决方案:

You can create an AWS Events Bridge Rule and set a Lambda function as the target using its ARN.您可以创建 AWS事件桥规则并使用其 ARN 将 Lambda function 设置为目标 You can specify a rate or cron schedule expression.您可以指定速率或 cron 计划表达式。 For example, the following expression will run your Lambda function after every ten minutes on all weekdays .例如,以下表达式将在所有 weekdays 每十分钟后运行您的 Lambda function 。

schedule = "cron(0/10 * ? * MON-FRI *)"

Note that your EventsBridge role will also require the lambda:InvokeFunction permission so EventsBridge can trigger your Lambda function.请注意,您的 EventsBridge 角色还需要lambda:InvokeFunction权限,因此 EventsBridge 可以触发您的 Lambda function。

Here's a full tutorial for the Terraform setup for this architecture: https://medium.com/geekculture/terraform-setup-for-scheduled-lambda-functions-f01931040007这是此架构的 Terraform 设置的完整教程: https://medium.com/geekculture/terraform-setup-for-scheduled-lambda-functions-f01931040007

Diksha is AWS Lambda Scheduler based on AWS SWF Trigger as recommended by AWS Team . Diksha 是AWS 团队推荐的基于 AWS SWF 触发器的 AWS Lambda 调度程序。 One can schedule jobs using cron expressions and can also specify how many time you want to run, when to start or when to end.可以使用 cron 表达式安排作业,还可以指定要运行的时间、何时开始或何时结束。 You can view status as well as history of scheduled jobs.您可以查看计划作业的状态和历史记录。 Security is managed by AWS policies.安全性由 AWS 策略管理。

Once you set up diksha engine, you can schedule functions using cron expression in following way:设置 diksha 引擎后,您可以通过以下方式使用 cron 表达式调度函数:

java -jar diksha-client-0.0.1.jar -lcfg cf1 -cj "jobName|functionName|context|0 0-59 * * * *|10" java -jar diksha-client-0.0.1.jar -lcfg cf1 -cj "jobName|functionName|context|0 0-59 * * * *|10"

In this job job will run every minute for 10 times.在此作业中,作业将每分钟运行 10 次。 AWS SWF will trigger function by itself. AWS SWF 将自行触发功能。

Details: https://github.com/milindparikh/diksha详情: https : //github.com/milindparikh/diksha

Disclaimer: I am contributor to the project.免责声明:我是该项目的贡献者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM