Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in AWS by (5.6k points)
My question, Is it possible to dynamically set a time for Lambda to be triggered from within the Lambda?

1 Answer

0 votes
by (12.4k points)

Yes, this can be done by setting the CloudWatch Event to trigger Lambda function, providing sample code:

var AWS = require("aws-sdk");

exports.handler = function(event, context) {

    var cloudwatchevents = new AWS.CloudWatchEvents();

    var intervals = Array(3, 5, 7);

    var nextInterval = intervals[Math.floor(Math.random()*intervals.length)];

    var currentTime = new Date().getTime(); // UTC Time

    var nextTime = dateAdd(currentTime, "minute", nextInterval);

    var nextMinutes = nextTime.getMinutes();

    var nextHours = nextTime.getHours();

    //  =================================

    //  DO YOUR WORK HERE

    //  =================================

    var scheduleExpression = "cron(" + nextMinutes + " " + nextHours + " * * ? *)";

    var params = {

        Name: "YOUR CLOUDWATCH EVENT RULE NAME",

        ScheduleExpression: scheduleExpression

    };

    cloudwatchevents.putRule(params, function(err, data) {

        if (err) {

            console.log(err, err.stack);  

        }

        else {

            console.log(data);

        }

    })

};

var dateAdd = function(date, interval, units) {

    var ret = new Date(date); // don't change original date

    switch(interval.toLowerCase()) {

        case 'year'   :  ret.setFullYear(ret.getFullYear() + units);  break;

        case 'quarter':  ret.setMonth(ret.getMonth() + 3*units);  break;

        case 'month'  :  ret.setMonth(ret.getMonth() + units);  break;

        case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;

        case 'day'    :  ret.setDate(ret.getDate() + units);  break;

        case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;

        case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;

        case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;

        default       :  ret = undefined;  break;

    }

    return ret;

}

here change the cloud watch event name.

Hope this helps.

Interested in learning AWS? Check out: AWS Online training

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
asked Dec 13, 2020 in AWS by Justin (7k points)
0 votes
1 answer

Browse Categories

...