Applicable when
- We need to execute some logic on a regular basis
Implementation
Lambda handler:
import { ScheduledEvent } from 'aws-lambda';
export async function handler(event: ScheduledEvent): Promise<void> {
// Some logic here that needs to be executed as a cron job
}
CDK configuration:
import { Rule, Schedule } from '@aws-cdk/aws-events';
import { LambdaFunction as TargetLambdaFunction } from '@aws-cdk/aws-events-targets';
import { Function as LambdaFunction } from '@aws-cdk/aws-lambda';
export class LambdaCron extends Construct {
constructor(scope: Construct) {
super(scope, 'Cron');
this.stopModels();
}
private stopModels(): void {
// configure lambda
const lambda = new LambdaFunction(this, lambdaName, {
handler: lambdaHandlerPath,
functionName: lambdaName,
runtime: Runtime.NODEJS_12_X,
code: Code.fromAsset(LAMBDA_CODE_PATH),
timeout: Duration.minutes(FIVE),
});
// Run every day at 7PM UTC
const rule = new Rule(this, 'StopModelsRule', {
schedule: Schedule.cron({ minute: '0', hour: '19' }),
});
rule.addTarget(new TargetLambdaFunction(lambda));
}
}
Comments
0 comments
Please sign in to leave a comment.