Create App Engine tasks programmatically

This document demonstrates how to programmatically create App Engine tasks and place them in Cloud Tasks queues.

Using this process you can explicitly specify the service and handler that should process the task, and optionally pass task-specific data along to the handler. The Cloud Tasks service forwards the task request to the handler, but this worker is located within App Engine. So all queues that target App Engine handlers must have an App Engine app. The handlers must run in the region where the App Engine app runs. This region also serves as the LOCATION_ID parameter for your Cloud Tasks requests. For more information, see Cloud Tasks queues with App Engine targets.

You can fine-tune the configuration for the task, like scheduling a time in the future when it should be executed or limiting the number of times you want the task to be retried if it fails. If you chose to specify a name for the task, Cloud Tasks can use that name to ensure task deduplication, although the processing necessary for this can add increased latency.

You can also create App Engine tasks by using the Google Cloud CLI or by sending a direct request to the Cloud Tasks API. For more information, see Create tasks.

App Engine firewall rules

In the App Engine standard environment, the App Engine firewall can allow certain internal traffic to bypass the firewall. This means that if you set the default rule to deny, requests from certain services destined for the App Engine standard environment don't get blocked. These are all types of traffic requested in the app's own configuration, or sent from the same app. Requests that bypass firewall rules in this way also include App Engine tasks in Cloud Tasks (including App Engine Task Queues).

To allow incoming requests, the following are the IP ranges for App Engine tasks in Cloud Tasks (including App Engine Task Queues):

  • IP range for requests sent to the App Engine standard environment: 0.1.0.2/32 (bypasses the default firewall rule if set to deny)

  • IP range for requests sent to the App Engine flexible environment: 0.1.0.2/32

Create tasks using the client libraries

You create tasks in the form of an HTTP request, which you can construct as you like. Using the client libraries however, as the following samples do, can help you manage details of low level communication with the server, including authenticating with Google. For adding a task to a queue, see Add a task to a Cloud Tasks queue

C#


using Google.Cloud.Tasks.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System;

class CreateAppEngineTask
{
    public string CreateTask(
        // TODO<developer>: call this method by passing correct values for
        // the following parameters or change the parameters' default values.
        string projectId = "YOUR-PROJECT-ID",
        string location = "us-central1",
        string queue = "my-queue",
        string payload = "Hello World!",
        int inSeconds = 0)
    {
        CloudTasksClient client = CloudTasksClient.Create();
        QueueName parent = new QueueName(projectId, location, queue);

        var response = client.CreateTask(new CreateTaskRequest
        {
            Parent = parent.ToString(),
            Task = new Task
            {
                AppEngineHttpRequest = new AppEngineHttpRequest
                {
                    HttpMethod = HttpMethod.Post,
                    RelativeUri = "/log_payload",
                    Body = ByteString.CopyFromUtf8(payload)
                },
                ScheduleTime = Timestamp.FromDateTime(
                    DateTime.UtcNow.AddSeconds(inSeconds))
            }
        });

        Console.WriteLine($"Created Task {response.Name}");
        return response.Name;
    }
}

Go


// Command create_task constructs and adds a task to an App Engine Queue.
package main

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
	taskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb"
)

// createTask creates a new task in your App Engine queue.
func createTask(projectID, locationID, queueID, message string) (*taskspb.Task, error) {
	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	// Build the Task queue path.
	queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID)

	// Build the Task payload.
	// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#AppEngineHttpRequest
			MessageType: