AWS Lambda functions can be triggered by a number of sources, for instance an asynchronous HTTP request. We may want to be a bit more synchronous - for instance trigger a function every X minutes, hours or days.
In this lesson we're going to build a simple "clock" function which is going to log the current time to CloudWatch logs every minute using rate expressions
Tomasz Lakomy: [0:00] We're going to start by creating a new Lambda function. I'm going to alter it from scratch, and I'm going to call it, "MyClock." I'm going to use Node.js, leave everything as default, and click on "Create function."
[0:10] This function is going to be a clock. Inside of this function, I'm going to leave everything as default, but I'm going to console.log('The time is'), and I'm going to log the new Date() object. Since this is a clock, we would like to call this function every minute and see the time in the CloudWatch Logs.
[0:27] In order to do that, we need to add a CloudWatch trigger. Click on "Add trigger," and we're going to select the CloudWatch Events as our trigger. We're going to create a new rule and I'm going to call it, "MyClockRule." You can add a description if you want. You can either use an "Event pattern," or we're going to "Schedule an expression."
[0:47] You can either use a "Cron" or something that's called a "rate expression." Rate expressions are easier for those very simple example, so I'm going to use dots. I'm going to call this function with a rate of one minute. It's going to be called every single minute.
[1:02] You can either enable the trigger right now, or you can create this trigger in a disabled state for testing, which can be useful in order to avoid excess charges. Right now, it's going to be called every minute. I don't care this much about cost, because Lambda is free for the first minute request, so I'm going to add this trigger right now.
[1:21] You can see over here that my trigger has been successfully added to this function, "MyClock." Right now, this function is called every single minute. I'm going to pause this video and come back in a couple of minutes in order to view the logs.
[1:33] Welcome back. Let's go to "Monitoring" and click on "View logs in CloudWatch." Click on the log stream, and we can see our clock in action. Over here, we can see that this function was called every minute since this trigger was created.