App Engine 태스크 만들기

App Engine 앱에 전송할 태스크 만들기

이 코드 샘플이 포함된 문서 페이지

컨텍스트에서 사용된 코드 샘플을 보려면 다음 문서를 참조하세요.

코드 샘플


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

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

class CreateAppEngineTask
    public string CreateTask(
        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;


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

// 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: %v", 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: %v", err)

	return createdTask, nil


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

// Instantiates a client.
try (CloudTasksClient client = CloudTasksClient.create()) {

  // Variables provided by the CLI.
  // projectId = "my-project-id";
  // queueName = "my-appengine-queue";
  // location = "us-central1";
  // payload = "hello";

  // 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()))

  if (params.hasOption(IN_SECONDS_OPTION.getOpt())) {
    // Add the scheduled time to the request.
    int seconds = Integer.parseInt(params.getOptionValue(IN_SECONDS_OPTION.getOpt()));

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


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

// 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: {
      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, task};
  const [response] = await client.createTask(request);
  const name =;
  console.log(`Created task ${name}`);


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

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());


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

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

from import tasks_v2
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

# 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.
    timestamp = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)

    # 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('Created task {}'.format(
return response


Cloud Tasks용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Tasks 클라이언트 라이브러리를 참조하세요.

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