建立 HTTP 目標工作

在 Beta 版 HTTP 目標的支援下,Cloud Tasks 處理常式現在可以在任何具備公開 IP 位址的 HTTP 端點上執行,例如 Cloud FunctionsCloud RunGKECompute Engine,甚至是內部部署的網路伺服器。您的工作可以在上述任一服務中以可靠且可供設定的方式執行。

本頁面說明如何透過程式建立 HTTP 目標工作,並排入 Cloud Tasks 佇列。一般來說,您可以透過 HTTP 要求的形式來建立工作。不過就如同下列範例所示,使用 Google Cloud 用戶端程式庫服務帳戶有助您管理與 Cloud Tasks 伺服器之間的通訊詳細資料,建立工作也變得更為容易。

HTTP 目標工作

以下範例會建立建構工作的 HTTP 目標工作要求,其中包含工作處理常式的網址。

C#

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

class CreateHttpTask
{
    public string CreateTask(
        string projectId = "YOUR-PROJECT-ID",
        string location = "us-central1",
        string queue = "my-queue",
        string url = "http://example.com/taskhandler",
        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
            {
                HttpRequest = new HttpRequest
                {
                    HttpMethod = HttpMethod.Post,
                    Url = url,
                    Body = ByteString.CopyFromUtf8(payload)
                },
                ScheduleTime = Timestamp.FromDateTime(
                    DateTime.UtcNow.AddSeconds(inSeconds))
            }
        });

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

Python

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

from google.cloud import tasks_v2beta3
from google.protobuf import timestamp_pb2

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

# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-queue'
# location = 'us-central1'
# url = 'https://example.com/task_handler'
# payload = 'hello'

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

# Construct the request body.
task = {
        'http_request': {  # Specify the type of request.
            'http_method': 'POST',
            'url': url  # The full url path that the task will be sent to.
        }
}
if payload is not None:
    # The API expects a payload of type bytes.
    converted_payload = payload.encode()

    # Add the payload to the request.
    task['http_request']['body'] = converted_payload

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

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

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

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

print('Created task {}'.format(response.name))
return response

請注意 requirements.txt 檔案:

Flask==1.0.2
gunicorn==19.9.0
google-cloud-tasks==0.7.0

Java

import com.google.cloud.tasks.v2beta3.CloudTasksClient;
import com.google.cloud.tasks.v2beta3.HttpMethod;
import com.google.cloud.tasks.v2beta3.HttpRequest;
import com.google.cloud.tasks.v2beta3.QueueName;
import com.google.cloud.tasks.v2beta3.Task;
import com.google.protobuf.ByteString;
import java.nio.charset.Charset;

public class CreateHttpTask {

  public static void main(String[] args) throws Exception {
    String projectId = System.getenv("PROJECT_ID");
    String queueName = System.getenv("QUEUE_ID");
    String location = System.getenv("LOCATION_ID");
    String url = System.getenv("URL");

    // Instantiates a client.
    try (CloudTasksClient client = CloudTasksClient.create()) {
      // Variables provided by the system variables.
      // projectId = "my-project-id";
      // queueName = "my-queue";
      // location = "us-central1";
      // url = "https://example.com/taskhandler";
      String payload = "hello";

      // Construct the fully qualified queue name.
      String queuePath = QueueName.of(projectId, location, queueName).toString();

      // Construct the task body.
      Task.Builder taskBuilder =
          Task.newBuilder()
              .setHttpRequest(
                  HttpRequest.newBuilder()
                      .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
                      .setUrl(url)
                      .setHttpMethod(HttpMethod.POST)
                      .build());

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

請注意 pom.xml 檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2018 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

       http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <groupId>com.example.task</groupId>
  <artifactId>tasks-samples</artifactId>

  <!--
    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.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.0.11</version>
    <relativePath></relativePath>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>

  <dependencies>
    <!-- Compile/runtime dependencies -->
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-tasks</artifactId>
      <version>0.88.0-beta</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.4.0</version>
        <executions>
          <execution>
              <id>HttpTask</id>
              <goals>
                  <goal>java</goal>
              </goals>
              <configuration>
                <mainClass>com.example.task.CreateHttpTask</mainClass>
                <cleanupDaemonThreads>false</cleanupDaemonThreads>
              </configuration>
          </execution>
          <execution>
              <id>WithToken</id>
              <goals>
                  <goal>java</goal>
              </goals>
              <configuration>
                <mainClass>com.example.task.CreateHttpTaskWithToken</mainClass>
                <cleanupDaemonThreads>false</cleanupDaemonThreads>
              </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

PHP

use Google\Cloud\Tasks\V2beta3\CloudTasksClient;
use Google\Cloud\Tasks\V2beta3\HttpMethod;
use Google\Cloud\Tasks\V2beta3\HttpRequest;
use Google\Cloud\Tasks\V2beta3\Task;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The Location ID';
// $queueId = 'The Cloud Tasks Queue ID';
// $url = 'The full url path that the task request will be sent to.'
// $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 Http Request Object.
$httpRequest = new HttpRequest();
// The full url path that the task request will be sent to.
$httpRequest->setUrl($url);
// POST is the default HTTP method, but any HTTP method can be used.
$httpRequest->setHttpMethod(HttpMethod::POST);
// Setting a body value is only compatible with HTTP POST and PUT requests.
if (isset($payload)) {
    $httpRequest->setBody($payload);
}

// Create a Cloud Task object.
$task = new Task();
$task->setHttpRequest($httpRequest);

// 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.0.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^5",
        "google/cloud-tools": "^0.8.5"
    }
}

Go

// Command createHTTPtask constructs and adds a task to a Cloud Tasks Queue.
package main

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2beta3"
	taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
)

// createHTTPTask creates a new task in your with a HTTP target.
func createHTTPTask(projectID, locationID, queueID, url, message string) (*taskspb.Task, error) {

	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2beta3
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %v", err)
	}

	// 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/v2beta3#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2beta3#HttpRequest
			PayloadType: &taskspb.Task_HttpRequest{
				HttpRequest: &taskspb.HttpRequest{
					HttpMethod: taskspb.HttpMethod_POST,
					Url:        url,
				},
			},
		},
	}

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

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

	return createdTask, nil
}

Node.js

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

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

// TODO(developer): Uncomment these lines and replace with your values.
// const project = 'my-project-id';
// const queue = 'my-queue';
// const location = 'us-central1';
// const url = 'https://example.com/taskhandler'
// const payload = 'hello';

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

const task = {
  httpRequest: {
    httpMethod: 'POST',
    url, //The full url path that the request will be sent to.
  },
};

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

if (inSeconds) {
  task.scheduleTime = {
    seconds: inSeconds + Date.now() / 1000,
  };
}

const request = {
  parent: parent,
  task: task,
};

console.log('Sending task:');
console.log(task);
// Send create task request.
const [response] = await client.createTask(request);
const name = response.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": ">=8"
  },
  "scripts": {
    "test": "mocha",
    "start": "node server.js"
  },
  "dependencies": {
    "@google-cloud/tasks": "^1.0.0",
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "yargs": "^13.0.0"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^6.1.3",
    "uuid": "^3.3.2"
  }
}

Ruby

require "google/cloud/tasks"

# Create a Task with an HTTP Target
#
# @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 Tasks Queue ID.
# @param [String] url The full path to sent the task request to.
# @param [String] payload The request body of your task.
# @param [Integer] seconds The delay, in seconds, to process your task.
def create_http_task project_id, location_id, queue_id, url, payload: nil, seconds: nil
  # Instantiates a client.
  client = Google::Cloud::Tasks.new

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

  # Construct task.
  task = {
    http_request: {
      http_method: "POST",
      url:         url
    }
  }

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

  # Add scheduled time to task.
  if seconds
    timestamp = Google::Protobuf::Timestamp.new
    timestamp.seconds = Time.now.to_i + seconds.to_i
    task[:schedule_time] = timestamp
  end

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

  if response.name
    puts "Created task #{response.name}"
  end
end

設定服務帳戶以驗證 HTTP 目標處理常式

如果您的專案服務帳戶具備存取處理常式的適當憑證,Cloud Tasks 即可呼叫需要驗證的 HTTP 目標處理常式。

  1. 識別可用於從 Cloud Tasks 到 HTTP 目標處理常式進行呼叫的現有服務帳戶,或是針對此用途建立新的服務帳戶。這是用戶端服務帳戶。

  2. 如果您的處理常式為 GCP 的一部分,請授予帳戶必要的身分與存取權管理角色,以更新用戶端服務帳戶。GCP 中的每項服務都需要不同的角色。例如,Cloud Run 需要 Cloud Run Invoker 角色等。

  3. Cloud Tasks 本身必須具備自己的服務帳戶,且該帳戶須被授予 Cloud Tasks Service Agent 角色,這樣才能代表您的用戶端服務帳戶產生標頭憑證,藉此對處理常式目標進行驗證。當您啟用 Cloud Scheduler API 時,系統會自動建立 Cloud Tasks 服務帳戶並授予此角色,「但」如果您在 2019 年 3 月 19 日之前啟用,則必須手動新增角色

具備驗證憑證的 HTTP 目標工作

如要在 Cloud Tasks 和 HTTP 目標處理常式之間進行驗證,Cloud Tasks 會依據用戶端服務帳戶建立標頭憑證 (由電子郵件識別),並且透過 HTTPS 傳送到處理常式。您可以使用 OIDC 憑證或 OAuth 憑證。一般狀況會使用 OIDC,但 *.googleapis.com 上託管的 Google API「除外」:這些 API 預期會使用 OAuth 憑證。您可以在要求本身中指定 OIDC 或 OAuth。

以下範例會建立工作要求,其中包含標頭憑證的建立。這些範例會使用 OIDC 憑證,如要使用 OAuth 憑證,請在建構要求中將 OIDC 參數替換為適當的 OAuth 參數語言。

Python

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

from google.cloud import tasks_v2beta3
from google.protobuf import timestamp_pb2

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

# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-queue'
# location = 'us-central1'
# url = 'https://example.com/task_handler'
# payload = 'hello'

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

# Construct the request body.
task = {
        'http_request': {  # Specify the type of request.
            'http_method': 'POST',
            'url': url,  # The full url path that the task will be sent to.
            'oidc_token': {
                'service_account_email': service_account_email
            }
        }
}

if payload is not None:
    # The API expects a payload of type bytes.
    converted_payload = payload.encode()

    # Add the payload to the request.
    task['http_request']['body'] = converted_payload

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

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

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

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

print('Created task {}'.format(response.name))
return response

請注意 requirements.txt 檔案:

Flask==1.0.2
gunicorn==19.9.0
google-cloud-tasks==0.7.0

Java

import com.google.cloud.tasks.v2beta3.CloudTasksClient;
import com.google.cloud.tasks.v2beta3.HttpMethod;
import com.google.cloud.tasks.v2beta3.HttpRequest;
import com.google.cloud.tasks.v2beta3.OidcToken;
import com.google.cloud.tasks.v2beta3.QueueName;
import com.google.cloud.tasks.v2beta3.Task;
import com.google.protobuf.ByteString;
import java.nio.charset.Charset;

public class CreateHttpTaskWithToken {

  public static void main(String[] args) throws Exception {
    String projectId = System.getenv("PROJECT_ID");
    String queueName = System.getenv("QUEUE_ID");
    String location = System.getenv("LOCATION_ID");
    String url = System.getenv("URL");

    // Instantiates a client.
    try (CloudTasksClient client = CloudTasksClient.create()) {
      // Variables provided by the system variables.
      // projectId = "my-project-id";
      // queueName = "my-queue";
      // location = "us-central1";
      // url = "https://example.com/taskhandler";
      String payload = "hello";

      // Construct the fully qualified queue name.
      String queuePath = QueueName.of(projectId, location, queueName).toString();

      // Add your service account email to construct the OIDC token.
      // in order to add an authentication header to the request.
      OidcToken.Builder oidcTokenBuilder =
          OidcToken.newBuilder().setServiceAccountEmail("<SERVICE_ACCOUNT_EMAIL>");

      // Construct the task body.
      Task.Builder taskBuilder =
          Task.newBuilder()
              .setHttpRequest(
                  HttpRequest.newBuilder()
                      .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
                      .setHttpMethod(HttpMethod.POST)
                      .setUrl(url)
                      .setOidcToken(oidcTokenBuilder)
                      .build());

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

請注意 pom.xml 檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2018 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

       http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <groupId>com.example.task</groupId>
  <artifactId>tasks-samples</artifactId>

  <!--
    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.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.0.11</version>
    <relativePath></relativePath>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>

  <dependencies>
    <!-- Compile/runtime dependencies -->
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-tasks</artifactId>
      <version>0.88.0-beta</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.4.0</version>
        <executions>
          <execution>
              <id>HttpTask</id>
              <goals>
                  <goal>java</goal>
              </goals>
              <configuration>
                <mainClass>com.example.task.CreateHttpTask</mainClass>
                <cleanupDaemonThreads>false</cleanupDaemonThreads>
              </configuration>
          </execution>
          <execution>
              <id>WithToken</id>
              <goals>
                  <goal>java</goal>
              </goals>
              <configuration>
                <mainClass>com.example.task.CreateHttpTaskWithToken</mainClass>
                <cleanupDaemonThreads>false</cleanupDaemonThreads>
              </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Go

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2beta3"
	taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
)

// createHTTPTaskWithToken constructs a task with a authorization token
// and HTTP target then adds it to a Queue.
func createHTTPTaskWithToken(projectID, locationID, queueID, url, email, message string) (*taskspb.Task, error) {
	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2beta3
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %v", err)
	}

	// 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/v2beta3#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2beta3#HttpRequest
			PayloadType: &taskspb.Task_HttpRequest{
				HttpRequest: &taskspb.HttpRequest{
					HttpMethod: taskspb.HttpMethod_POST,
					Url:        url,
					AuthorizationHeader: &taskspb.HttpRequest_OidcToken{
						OidcToken: &taskspb.OidcToken{
							ServiceAccountEmail: email,
						},
					},
				},
			},
		},
	}

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

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

	return createdTask, nil
}

Node.js

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

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

// TODO(developer): Uncomment these lines and replace with your values.
// const project = 'my-project-id';
// const queue = 'my-queue';
// const location = 'us-central1';
// const url = 'https://example.com/taskhandler'
// const email = 'client@<project-id>.iam.gserviceaccount.com'
// const payload = 'hello';

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

const task = {
  httpRequest: {
    httpMethod: 'POST',
    url, //The full url path that the request will be sent to.
    oidcToken: {
      serviceAccountEmail: email,
    },
  },
};

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

if (inSeconds) {
  task.scheduleTime = {
    seconds: inSeconds + Date.now() / 1000,
  };
}

const request = {
  parent: parent,
  task: task,
};

console.log('Sending task:');
console.log(task);
// Send create task request.
const [response] = await client.createTask(request);
const name = response.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": ">=8"
  },
  "scripts": {
    "test": "mocha",
    "start": "node server.js"
  },
  "dependencies": {
    "@google-cloud/tasks": "^1.0.0",
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "yargs": "^13.0.0"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^6.1.3",
    "uuid": "^3.3.2"
  }
}

自行提供 HTTP 目標工作處理常式

HTTP 目標工作處理常式與 App Engine 工作處理常式非常類似,除了:

  • 逾時:針對所有 HTTP 目標工作處理常式,預設逾時為 10 分鐘,最多為 30 分鐘。
  • 驗證邏輯:如要透過在目標服務中寫入自有的程式碼來驗證憑證,您應使用 OIDC 憑證。如要進一步瞭解相關必要內容,請參閱 OpenID Connect,尤其是驗證 ID 憑證一節。

手動新增 Cloud Tasks 服務代理人角色到 Cloud Tasks 服務帳戶

只有當您在 2019 年 3 月 19 日之前啟用 Cloud Tasks API 時,才需要執行此操作。

使用主控台

  1. GCP「Project Settings」(專案設定) 頁面中找出專案的專案編號。
  2. 複製編號。
  3. 開啟主控台的「IAM Admin」(IAM 管理員) 頁面
  4. 按一下 AddAdd members 畫面會隨即開啟。
  5. 在「New members」(新增成員) 文字方塊中,新增此格式的電子郵件地址。

    service-[project-number]@gcp-sa-cloudtasks.iam.gserviceaccount.com
    

    將上述的「[project-number]」替換為您的專案編號。

  6. Select a role 下拉式選單中選擇 Service Management -> Cloud Tasks Service Agent

  7. 按一下 Save

使用 gcloud

  1. 找出專案編號:

    gcloud projects describe [project-id] --format='table(projectNumber)'
    

    將「[PROJECT-ID]」替換為您的專案 ID。

  2. 複製編號。

  3. 使用您複製的專案編號,授予 Cloud Tasks 服務帳戶 Cloud Tasks Service Agent 角色:

    gcloud projects add-iam-policy-binding [project-id] --member serviceAccount:service-[project-number]@gcp-sa-cloudtasks.iam.gserviceaccount.com --role roles/cloudtasks.serviceAgent
    

    將上述「[PROJECT-ID]」替換為您的專案 ID,接著將「[project-number]」替換為專案編號。

後續步驟

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Tasks 說明文件