This article was written by Rene Brandel, Senior Product Manager AWS Amplify

In this post, you’ll learn to schedule recurring Lambda functions, a new capability released with the newest version of the Amplify CLI. This capability allows customers to schedule Lambda functions to be executed periodically (e.g every minute, hourly, daily, weekly, monthly or yearly basis).

In this post, we’ll use Amplify CLI to create a Lambda function that sends you “cat fact“-email every 2 hours.

What we’ll use:

  • Amplify CLI to create, test, schedule and deploy the Lambda function
  • /facts API from catfact.ninja to retrieve a random cat fact
  • nodemailer to send an email to our Mailtrap.io (an e-mail testing platform) inbox

ezgif.com video to gif

Pre-requisites:

  • Install the latest Amplify CLI version – Open terminal and run npm install -g @aws-amplify/cli to update to the latest Amplify CLI.
  • Amplify CLI is already configured – If you haven’t configured the Amplify CLI yet, follow this guide on our documentation page.
  • You have a Mailtrap.io account – We will use Mailtrap.io to easily simulate an email client. The service is free and it’s only a couple of clicks to sign-up.

1. Setup your environment

First, let’s create your project directory by running the following command. If you have an existing Amplify project, you can skip to the next section.

mkdir hourly-cat-fact

Let’s change directory into the newly created project:

cd hourly-cat-fact

In the project directory initialize a new Amplify project:

amplify init

For the sake of this example, you’re good by just accepting all default values. So the selection & output should look something like this.

? Enter a name for the project (hourly-cat-fact)
? Enter a name for the environment (dev)
? Choose your default editor: (Visual Studio Code)
? Choose the type of app that you're building (javascript)

Please tell us about your project

? What javascript framework are you using (none)
? Source Directory Path: (src)
? Distribution Directory Path: (dist)
? Build Command: (npm run-script build)
? Start Command: (npm run-script start)

Using default provider awscloudformation For more information on AWS Profiles, see: https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

? Do you want to use an AWS profile? (Yes)
? Please choose the profile you want to use (default)

2. Add your Lambda function

Amplify makes it easy to create, test and deploy Lambda functions. To create a function, run the add command:

amplify add function

Follow the selections as indicated below:

? Provide a friendly name for your resource to be used as a label for this category in the project: catFact
? Provide the AWS Lambda function name: catFact
? Choose the function template that you want to use: Hello World
? Do you want to access other resources created in this project from your Lambda function? No

Then you’ll be asked if you want to schedule this function. Answer Yes.

? Do you want to invoke this function on a recurring schedule? Yes
? At which interval should the function be invoked: Hourly
? Enter the rate in hours: 2
? Do you want to edit the local lambda function now? No

Now you can choose the interval and rate at which the function executes. While for this demo, we want to receive emails every 2 hours. You can also formulate more complex schedules using AWS Cron Expressions such as: “10:15 AM on the last Friday of every month”. Review the Schedule Expression for Rules documentation for more details.

We’ll skip editing the Lambda function now because we’ll need to install a couple dependencies first.

3. Install node dependencies

In order to retrieve a cat fact and send it via email, we need to install two NPM packages:

  1. node-fetch – A light-weight module that brings window.fetch to Node.js
  2. nodemailer – An easy-to-use package to send emails using Node.js

Navigate to the catFact function’s source folder by running the following command:

cd amplify/backend/function/catFact/src

Run the following command in the function’s folder to install the dependencies:

npm install -S node-fetch nodemailer

4. Retrieve cat facts and send them out

With the dependencies installed, we can finally get to the code. Replace your function’s code with the snippet below. We’ll be using the /facts API provided by catfact.ninja. It’s as easy as issuing a GET request and parsing the fact object from the JSON.

const nodemailer = require('nodemailer')
const fetch = require('node-fetch')

exports.handler = async (event, context, callback) => {
    // setup nodemailer
    const transporter = nodemailer.createTransport({
        host: "smtp.mailtrap.io",
        port: 587,
        auth: {
            user: "MAILTRAP_USERNAME", //generated by Mailtrap
            pass: "MAILTRAP_PASSWORD" //generated by Mailtrap
        }
    });

    // gather cat fact
    const fact = await fetch('https://catfact.ninja/fact')
        .then(res => res.json())
        .then(json => json.fact)
        .catch(err => callback(Error(err)))
        
    const message = {
        from: '[email protected]', // Sender address
        to: '[email protected]',         // List of recipients
        subject: '😸Your hourly cat fact!', // Subject line
        text: fact // Plain text body
    };

    // sends the email
    await transporter.sendMail(message)
};

Make sure to replace MAILTRAP_USERNAME and MAILTRAP_PASSWORD with your own credentials from your Mailtrap inbox.

To get the credentials, login to Mailtrap.io and select your inbox. The username and password are located in the SMTP Settings tab inside your Mailtrap inbox.

Screen Shot 2020 03 30 at 2.41.24 PM

There are many customization you can do for the message itself. To get a full picture of what’s possible, review the sendMail function’s documentation. You could easily expand this to also send GIFs and other rich media.

Now your function is ready to go. You can test locally by running amplify function invoke catFact and now let’s check in the Mailtrap inbox. You should see a new email about a cat fact.

5. Deploy the function

All you have to do is run amplify push and your function is deployed and will execute every 2 hours.
👏 Congratulations! You’ve successfully built a “cat fact” email service!

In this post, you’ve learned how to create a Lambda function with AWS Amplify CLI and schedule it to be invoked periodically. If you want to learn more about Amplify CLI or this capability in particular, please review our documentation.

 

ZB WbGaYwec

from AWS Mobile Blog: https://aws.amazon.com/blogs/mobile/how-to-schedule-recurring-lambda-functions-using-the-amplify-cli/