This tutorial shows you how to use Cloud Tasks within an App Engine application to trigger a Cloud Run function and send a scheduled email.
Objectives
- Understand the code in each of the components.
- Create a SendGrid account.
- Download the source code.
- Deploy a Cloud Run function to receive Cloud Tasks requests and send an email via the SendGrid API.
- Create a Cloud Tasks queue.
- Create a service account to authenticate your Cloud Tasks requests.
- Deploy the client code that allows a user to send an email.
Costs
Cloud Tasks, Cloud Run functions, and App Engine have a free tier, so as long as you are running the tutorial within the free tier of the given products it should not result in additional costs. For more information, see Pricing.
Before you begin
Select or create a Google Cloud project.
Initialize an App Engine application in your project:
On the Welcome to App Engine page click Create Application.
Select a region for your application. This location will serve as the
LOCATION_IDparameter for your Cloud Tasks requests, so make a note of it. Note that two locations, called europe-west and us-central in App Engine commands, are called, respectively, europe-west1 and us-central1 in Cloud Tasks commands.Select Node.js for the language and Standard for the environment.
If the Enable billing popup appears, select your billing account. If you do not currently have a billing account, click Create billing account and follow the wizard.
On the Get started page, click Next. You'll take care of this later.
Enable the Cloud Run functions and Cloud Tasks APIs.
Install and initialize the gcloud CLI.
Understanding the code
This section walks you through the app's code and explains how it works.
Creating the task
The index page is served using handlers in the app.yaml. The variables needed for task creation are passed in as environment variables.
This code creates the endpoint /send-email. This endpoint handles form submissions from the index page and passes that data to the task creation code.
This code actually creates the task and sends it on to the Cloud Tasks queue. The code builds the task by:
Specifying the target type as
HTTP Request.Specifying the
HTTP methodto be used and theURLof the target.Setting the
Content-Typeheader toapplication/jsonso downstream applications can parse the structured payload.Adding a service account email so that Cloud Tasks can provide credentials to the request target, which requires authentication. The service account is created separately.
Checking to make sure the user input for date is within the 30 days maximum and adding it to the request as field
scheduleTime.