App Engine 태스크 만들기

이 페이지에서는 프로그래매틱 방식으로 App Engine 작업을 만들어 Cloud Tasks 큐에 배치하는 방법을 설명합니다. 이 절차를 이용하여 태스크를 처리하는 서비스와 핸들러를 명시적으로 지정하고 필요에 따라 태스크별 데이터를 핸들러에 함께 전달할 수 있습니다. Cloud Tasks 서비스가 태스크 요청을 핸들러로 전달하지만 이 작업자는 App Engine 내에 있습니다. 따라서 App Engine 핸들러를 타겟팅하는 모든 큐에는 App Engine 앱이 있어야 합니다. 핸들러는 App Engine 앱이 실행되는 리전에서 실행되어야 합니다. 이 리전은 Cloud Tasks 요청의 LOCATION_ID 매개변수로도 사용됩니다. 자세한 내용은 App Engine 대상이 있는 Cloud Tasks 큐를 참조하세요.

태스크를 실행할 시간을 예약하거나 태스크가 실패할 경우 재시도할 횟수를 제한하는 등 태스크의 구성을 세부적으로 조정할 수도 있습니다. 태스크의 이름을 지정하면 Cloud Tasks에서 이 이름을 사용하여 태스크 중복 삭제를 보장할 수 있지만 필요한 처리로 인해 지연 시간이 늘어날 수 있습니다.

App Engine 방화벽 규칙

App Engine 표준 환경에서 App Engine 방화벽은 특정 내부 트래픽이 방화벽을 우회하도록 허용할 수 있습니다. 즉, default 규칙을 deny로 설정하면 App Engine 표준 환경을 대상으로 하는 특정 서비스의 요청이 차단되지 않습니다. 이는 앱 자체 구성에서 요청되거나 동일한 앱에서 전송되는 모든 유형의 트래픽입니다. 이러한 방식으로 방화벽 규칙을 우회하는 요청에는 Cloud Tasks의 App Engine 태스크(App Engine 태스크 큐 포함)도 포함됩니다.

수신 요청을 허용하려면 Cloud Tasks에서 App Engine 태스크(App Engine 태스크 큐 포함)에 다음과 같은 IP 범위를 사용해야 합니다.

  • App Engine 표준 환경으로 전송된 요청의 IP 범위:거부로 설정된 경우 기본 방화벽 규칙을 우회)

  • App Engine 가변형 환경으로 전송된 요청의 IP 범위:

클라이언트 라이브러리를 사용해 태스크 만들기

원하는 대로 구성할 수 있는 HTTP 요청 양식으로 태스크를 만듭니다. 그러나 클라이언트 라이브러리를 사용하면 아래의 예시와 같이 Google 인증 등 서버와의 통신에 대한 하위 수준의 세부정보 관리가 가능합니다. 큐에 태스크를 추가하려면 Cloud Tasks 큐에 태스크 추가를 참조하세요.


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(

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


"""Create a task for a given queue with an arbitrary payload."""

from import tasks_v2
from google.protobuf import timestamp_pb2
import datetime
import json

# Create a client.
client = tasks_v2.CloudTasksClient()

# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-appengine-queue'
# location = 'us-central1'
# payload = 'hello' or {'param': 'value'} for application/json
# in_seconds = None

# Construct the fully qualified queue name.
parent = client.queue_path(project, location, queue)

# Construct the request body.
task = {
    "app_engine_http_request": {  # Specify the type of request.
        "http_method": tasks_v2.HttpMethod.POST,
        "relative_uri": "/example_task_handler",
if payload is not None:
    if isinstance(payload, dict):
        # Convert dict to JSON string
        payload = json.dumps(payload)
        # specify http content-type to application/json
        task["app_engine_http_request"]["headers"] = {
            "Content-type": "application/json"
    # The API expects a payload of type bytes.
    converted_payload = payload.encode()

    # Add the payload to the request.
    task["app_engine_http_request"]["body"] = converted_payload

if in_seconds is not None:
    # Convert "seconds from now" into an rfc3339 datetime string.
    d = + datetime.timedelta(

    # Create Timestamp protobuf.
    timestamp = timestamp_pb2.Timestamp()

    # Add the timestamp to the tasks.
    task["schedule_time"] = timestamp

# Use the client to build and send the task.
response = client.create_task(parent=parent, task=task)

print(f"Created task {}")
return response

requirements.txt 파일을 확인합니다.

Flask==3.0.0; python_version > '3.6'
Flask==2.0.3; python_version < '3.7'


import java.nio.charset.Charset;
import java.time.Clock;
import java.time.Instant;

public class CreateTask {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String queue = "my-appengine-queue";
    String location = "us-central1";
    String payload = "hello";
    int seconds = 0; // Scheduled delay for the task in seconds
    createTask(projectId, queue, location, payload, seconds);

  // This is an example snippet for showing best practices.
  public static void createTask(
      String projectId, String queueName, String location, String payload, int seconds)
      throws IOException {
    // Instantiates a client.
    try (CloudTasksClient client = CloudTasksClient.create()) {
      // Construct the fully qualified queue name.
      String queuePath = QueueName.of(projectId, location, queueName).toString();

      // Construct the task body.
      Task.Builder taskBuilder =
                      .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))

      // Add the scheduled time to the request.

      // Send create task request.
      Task task = client.createTask(queuePath,;
      System.out.println("Task created: " + task.getName());

pom.xml 파일을 확인합니다.

<?xml version="1.0" encoding="UTF-8"?>
Copyright 2019 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 See the License for the specific language governing permissions and
 limitations under the License.
<project xmlns=""

    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.


  <!--  Using libraries-bom to manage versions.
  See -->

    <!-- Test dependencies -->



use Google\Cloud\Tasks\V2\AppEngineHttpRequest;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\HttpMethod;
use Google\Cloud\Tasks\V2\Task;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The Location ID';
// $queueId = 'The Cloud Tasks App Engine Queue ID';
// $payload = 'The payload your task should carry to the task handler. Optional';

// Instantiate the client and queue name.
$client = new CloudTasksClient();
$queueName = $client->queueName($projectId, $locationId, $queueId);

// Create an App Engine Http Request Object.
$httpRequest = new AppEngineHttpRequest();
// The path of the HTTP request to the App Engine service.
// POST is the default HTTP method, but any HTTP method can be used.
// Setting a body value is only compatible with HTTP POST and PUT requests.
if (isset($payload)) {

// Create a Cloud Task object.
$task = new Task();

// Send request and print the task name.
$response = $client->createTask($queueName, $task);
printf('Created task %s' . PHP_EOL, $response->getName());

composer.json 파일을 확인합니다.

    "require": {
        "google/cloud-tasks": "^1.4.0"


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

import (

	cloudtasks ""
	taskspb ""

// 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
	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.
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			MessageType: &taskspb.Task_AppEngineHttpRequest{
				AppEngineHttpRequest: &taskspb.AppEngineHttpRequest{
					HttpMethod:  taskspb.HttpMethod_POST,
					RelativeUri: "/task_handler",

	// Add a payload message if one is present.
	req.Task.GetAppEngineHttpRequest().Body = []byte(message)

	createdTask, err := client.CreateTask(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("cloudtasks.CreateTask: %w", err)

	return createdTask, nil


// Imports the Google Cloud Tasks library.
const {CloudTasksClient} = require('@google-cloud/tasks');

// Instantiates a client.
const client = new CloudTasksClient();

async function createTask() {
  // TODO(developer): Uncomment these lines and replace with your values.
  // const project = 'my-project-id';
  // const queue = 'my-appengine-queue';
  // const location = 'us-central1';
  // const payload = 'Hello, World!';

  // Construct the fully qualified queue name.
  const parent = client.queuePath(project, location, queue);

  const task = {
    appEngineHttpRequest: {
      headers: {
        'Content-Type': 'text/plain', // Set content type to ensure compatibility your application's request parsing
      httpMethod: 'POST',
      relativeUri: '/log_payload',

  if (payload) {
    task.appEngineHttpRequest.body = Buffer.from(payload).toString('base64');

  if (inSeconds) {
    // The time when the task is scheduled to be attempted.
    task.scheduleTime = {
      seconds: inSeconds + / 1000,

  console.log('Sending task:');

  // Send create task request.
  const request = {parent: parent, task: task};
  const [response] = await client.createTask(request);
  const name =;
  console.log(`Created task ${name}`);


package.json 파일을 확인합니다.

  "name": "appengine-cloudtasks",
  "description": "Google App Engine Cloud Tasks example.",
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "private": true,
  "engines": {
    "node": ">=16.0.0"
  "files": [
  "scripts": {
    "test": "c8 mocha -p -j 2 --timeout 30000",
    "start": "node server.js"
  "dependencies": {
    "@google-cloud/tasks": "^4.0.0",
    "express": "^4.16.3"
  "devDependencies": {
    "c8": "^8.0.0",
    "chai": "^4.2.0",
    "mocha": "^10.0.0",
    "uuid": "^9.0.0"


require "google/cloud/tasks"

# Create an App Engine Task
# @param [String] project_id Your Google Cloud Project ID.
# @param [String] location_id Your Google Cloud Project Location ID.
# @param [String] queue_id Your Google Cloud App Engine Queue ID.
# @param [String] payload The request body of your task.
# @param [Integer] seconds The delay, in seconds, to process your task.
def create_task project_id, location_id, queue_id, payload: nil, seconds: nil
  # Instantiates a client.
  client = Google::Cloud::Tasks.cloud_tasks

  # Construct the fully qualified queue name.
  parent = client.queue_path project: project_id, location: location_id, queue: queue_id

  # Construct task.
  task = {
    app_engine_http_request: {
      http_method:  "POST",
      relative_uri: "/log_payload"

  # Add payload to task body.
  if payload
    task[:app_engine_http_request][:body] = payload

  # Add scheduled time to task.
  if seconds
    timestamp =
    timestamp.seconds = + seconds.to_i
    task[:schedule_time] = timestamp

  # Send create task request.
  puts "Sending task #{task}"
  response = client.create_task parent: parent, task: task

  puts "Created task #{}" if

다음 단계