Serverless Frameworkでcron実行するサンプルコードです。
AWS LambdaではJST未対応のようで、-9時間する必要有ります。
時間設定の際にご留意ください。
ディレクトリ構成
~/develop/study/serverless/cron $ tree -I node_modules
.
└── aws-node-scheduled-cron
├── handler.js
├── package.json
├── serverless.yml
└── yarn.lock
serverless.yml
service: aws-node-scheduled-cron2
frameworkVersion: '2'
provider:
name: aws
runtime: nodejs12.x
lambdaHashingVersion: 20201221
functions:
cronHandler:
handler: handler.run
events:
- schedule: cron(0 1 * * ? *) #毎日10時に定期実行する。
※cronはUTC時間設定のため、-9時間する必要有り。
handler.ts
'use strict';
module.exports.run = async (event, context) => {
const time = new Date();
console.log(`${time} cron実行上手く動いてますよ!! `);
};
デプロイ
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
........
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service aws-node-scheduled-cron2.zip file to S3 (30.48 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.....................
Serverless: Stack update finished...
Service Information
service: aws-node-scheduled-cron2
stage: dev
region: ap-northeast-1
stack: aws-node-scheduled-cron2-dev
resources: 8
api keys:
None
endpoints:
None
functions:
cronHandler: aws-node-scheduled-cron2-dev-cronHandler
layers:
None