Search code examples
node.jscronserverlessnode-schedule

What will be the CRON expression to run CRON only once at particular date and time using lambda and serverless?


I added below block in serverless.yml file to schedule a CRON:

testCron1:
    handler: handler.testCron1
    events:
      - schedule: cron(15 14 22 MAY FRI 2020)

Then I create a testCron1 lambda function in handle.js file.

const testCron1 = (event, context) => {
    return new Promise(async (resolve, reject) => {
        console.log("*********** NEW est CRON ************");
        console.log("Current Time ==> ", new Date(moment().utc().format()));
        resolve(true);
    });
}

When I try to deploy using command serverless deploy, it gives me below error:

An error occurred: TestCron1EventsRuleSchedule1 - Parameter ScheduleExpression is not valid. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code:ValidationException; Request ID: c5b3178b-348a-4ffd-a205-d5255dcca2ab)

Solution

  • If you are using lambda use cloud watch as a cron trigger.

    it would be easy to handle the lambda function trigger at a particular time with cloud watch.

    you can find trigger rules expression here : https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html

    Supported value list you can check here : https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html

    Example cron : 0 11 17 4 ? 2020 min hours day month dayOfWeek year
    
    This will execute once on FRI, 17 APR 2020 11:00:00 GMT as an example.