0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

特定のLambdaを指定した時刻に実行する(Node.js)

Last updated at Posted at 2024-09-30

Lambdaで、自分自身を1分後に呼び出せるようにしてみました。

要約

  • EventBridge Schedulerを使用
  • 2種類のロールを用意する必要がある
    1. 実行ロール
    2. EventBridgeのスケジュールに付与するロール
  • 作成しようとしているスケジュールと同名のスケジュールがあるとエラーになるので、先に削除が必要

IAMロールの用意

1. 実行ロール

Lambdaで実行する場合、Lambdaの実行ロールに下記を含める

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "scheduler:CreateSchedule",
                "scheduler:DeleteSchedule",
                "iam:PassRole"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

2. EventBridgeのスケジュールに付与するロール

ResourceはLambdaのARNに置き換え

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "arn:aws:lambda:ap-northeast-1:123456789012:function:your-lambda-function-name:*",
                "arn:aws:lambda:ap-northeast-1:123456789012:function:your-lambda-function-name"
            ]
        }
    ]
}

パッケージのインストール

npm install @aws-sdk/client-scheduler

コード

createTrigger.js
import { SchedulerClient, CreateScheduleCommand, DeleteScheduleCommand } from "@aws-sdk/client-scheduler";

const region = "ap-northeast-1"; //リージョン
const ROLE_ARN = "arn:aws:iam::123456789012:role/service-role/your-eventbridge-role-lambda-executor"; // EventTriggerに付与する用のロールのARN(2)
const LAMBDA_ARN = "arn:aws:lambda:ap-northeast-1:123456789012:function:your-lambda-function-name"; // LambdaのARN
const SCHEDULE_NAME = "OneTimeTrigger"; // EventBridge Scheduler上での表示名。なんでもOK

const eventBridgeScheduler = new SchedulerClient({
    region,
    // AWSの外部で実行する場合は、1.実行ロール が付与されたIAMユーザーのアクセスキーも設定
    // credentials: {
    //    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    //    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
    // }
});

export const createSchedule = async () => {
    const lambdaTarget = {
        RoleArn: ROLE_ARN,
        Arn: LAMBDA_ARN
    };

    const delayInMinutes = 1; // 何分後に実行するか
    const scheduledTime = new Date(Date.now() + delayInMinutes * 60 * 1000);

    // 同名のスケジュールが既に存在する場合は削除する
    await eventBridgeScheduler.send(new DeleteScheduleCommand({ Name: SCHEDULE_NAME }));

    const command = new CreateScheduleCommand({
        Name: SCHEDULE_NAME,
        ScheduleExpression: `at(${scheduledTime.toISOString().slice(0, -5)})`,
        Target: lambdaTarget,
        FlexibleTimeWindow: { Mode: "OFF" },
    });

    try {
        const response = await eventBridgeScheduler.send(command);
        console.log("Schedule created successfully:", response);
    } catch (error) {
        console.error("Error creating schedule:", error);
    }
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?