Cloud Tasks は、Google Cloud Platform (GCP) が提供する非同期タスク実行サービスです。アプリケーションのタスクをキューに入れ、スケジュールし、実行することができます。これにより、バックグラウンド処理、長時間実行タスク、定期的なジョブなどを効率的に管理できます。Cloud Tasksは、タスクの配信保証、リトライ、レート制限などの機能を提供し、アプリケーションの信頼性と拡張性を向上させます。
Cloud Tasksは以下の主要コンポーネントで構成されています:
コンポーネント | 説明 |
---|---|
キュー | タスクを格納する論理的なコンテナ。キューごとに異なる構成(リトライ設定、レート制限など)を設定可能 |
タスク | 実行される個々の作業単位。HTTPリクエストまたはApp Engineタスクとして定義される |
ワーカー | タスクを処理するサービス。Cloud Run、Cloud Functions、App Engine、またはカスタムHTTPエンドポイント |
スケジューラ | タスクの実行タイミングを管理するコンポーネント |
ディスパッチャー | タスクをワーカーに送信し、レスポンスを処理するコンポーネント |
Cloud TasksとCloud Schedulerには以下のような違いがあります:
Cloud Tasksは、Google Cloud Console、gcloud CLIツール、クライアントライブラリ、またはRESTful APIを使用して利用できます。
gcloud tasks queues create my-queue \
--location=asia-northeast1
gcloud tasks queues update my-queue \
--location=asia-northeast1 \
--max-dispatches-per-second=5 \
--max-concurrent-dispatches=10 \
--max-attempts=5 \
--min-backoff=2s \
--max-backoff=10s \
--max-retry-duration=30s \
--max-doublings=3
gcloud tasks create-http-task \
--queue=my-queue \
--location=asia-northeast1 \
--url=https://example.com/process-task \
--method=POST \
--body-content='{"message":"Hello, World!"}' \
--header=Content-Type=application/json
gcloud tasks create-http-task \
--queue=my-queue \
--location=asia-northeast1 \
--url=https://example.com/process-task \
--schedule-time="2023-12-31T23:59:59Z"
const {CloudTasksClient} = require('@google-cloud/tasks');
const client = new CloudTasksClient();
async function createTask() {
const parent = client.queuePath('my-project', 'asia-northeast1', 'my-queue');
const task = {
httpRequest: {
httpMethod: 'POST',
url: 'https://example.com/process-task',
headers: {
'Content-Type': 'application/json',
},
body: Buffer.from(JSON.stringify({message: 'Hello, World!'})).toString('base64'),
},
};
// スケジュール時間の設定(オプション)
const date = new Date();
date.setSeconds(date.getSeconds() + 60); // 60秒後に実行
task.scheduleTime = {
seconds: parseInt(date.getTime() / 1000),
};
const [response] = await client.createTask({parent, task});
console.log(`Created task ${response.name}`);
return response;
}
createTask();
from google.cloud import tasks_v2
import json
import datetime
def create_task():
client = tasks_v2.CloudTasksClient()
parent = client.queue_path('my-project', 'asia-northeast1', 'my-queue')
payload = {'message': 'Hello, World!'}
payload_bytes = json.dumps(payload).encode()
task = {
'http_request': {
'http_method': tasks_v2.HttpMethod.POST,
'url': 'https://example.com/process-task',
'headers': {
'Content-Type': 'application/json',
},
'body': payload_bytes,
}
}
# スケジュール時間の設定(オプション)
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=60)
timestamp = datetime.datetime.timestamp(d)
task['schedule_time'] = {'seconds': int(timestamp)}
response = client.create_task(request={'parent': parent, 'task': task})
print(f'Created task {response.name}')
return response
create_task()
デッドレターキューを使用して、繰り返し失敗するタスクを別のキューに移動して処理できます:
gcloud tasks queues update my-queue \
--location=asia-northeast1 \
--dead-letter-queue=my-dead-letter-queue \
--max-attempts-per-task=5 \
--max-retry-attempts=5
レート制限を設定して、タスクの実行レートを制御し、バックエンドサービスの過負荷を防止できます:
gcloud tasks queues update my-queue \
--location=asia-northeast1 \
--max-dispatches-per-second=5 \
--max-concurrent-dispatches=10
リトライ設定をカスタマイズして、失敗したタスクの再試行動作を制御できます:
gcloud tasks queues update my-queue \
--location=asia-northeast1 \
--max-attempts=5 \
--min-backoff=2s \
--max-backoff=10s \
--max-retry-duration=30s \
--max-doublings=3
Cloud Tasksは、タスクの安全な実行を確保するための様々なセキュリティ機能を提供しています:
IAMを使用して、キューへのアクセスを制御できます:
# キューへのアクセス権を付与
gcloud tasks queues add-iam-policy-binding my-queue \
--location=asia-northeast1 \
--member=serviceAccount:my-service-account@my-project.iam.gserviceaccount.com \
--role=roles/cloudtasks.enqueuer
OIDCトークンを使用して、タスクハンドラーへのリクエストを認証できます:
gcloud tasks create-http-task \
--queue=my-queue \
--location=asia-northeast1 \
--url=https://example.com/process-task \
--oidc-token-audience=https://example.com \
--oidc-service-account-email=my-service-account@my-project.iam.gserviceaccount.com
VPCサービスコントロールを使用して、Cloud Tasksへのアクセスをセキュリティ境界内に制限できます。
Cloud TasksはGoogle Cloud Monitoringと統合されており、キューとタスクの状態を監視できます:
Cloud Loggingを使用して、タスクの実行ログを分析できます:
gcloud logging read 'resource.type="cloud_tasks_queue" AND resource.labels.queue_id="my-queue"'
Cloud Tasksは以下のようなユースケースに適しています:
Cloud Tasksは他のGoogle Cloudサービスと統合して、より強力なソリューションを構築できます:
サービス | 統合の利点 |
---|---|
Cloud Run | サーバーレス環境でタスクを処理し、需要に応じて自動的にスケール |
Cloud Functions | 軽量なタスク処理ロジックをサーバーレス関数として実装 |
App Engine | マネージド環境でタスクを処理し、App Engineの自動スケーリングを活用 |
Compute Engine | カスタムVMでより複雑なタスク処理を実行 |
Cloud Pub/Sub | イベント駆動型アーキテクチャの一部としてタスクを生成 |
Cloud Storage | ファイルのアップロードや変更に応じてタスクを生成 |
Cloud Scheduler | 定期的なタスクの生成とスケジューリング |
gcloud tasks create-http-task \
--queue=my-queue \
--location=asia-northeast1 \
--url=https://my-service-abcdef-uc.a.run.app/process-task \
--oidc-token-audience=https://my-service-abcdef-uc.a.run.app \
--oidc-service-account-email=my-service-account@my-project.iam.gserviceaccount.com
タスクが複数回実行されても安全なように、べき等性を確保する方法:
Cloud Tasks は、Google Cloud Platform上での非同期タスク処理を簡素化するフルマネージドサービスです。タスクのキューイング、スケジューリング、実行を管理し、アプリケーションの信頼性と拡張性を向上させます。
Cloud Tasksの主な利点は以下の通りです:
Cloud Tasksを効果的に活用するには、適切なキュー設計、べき等性の確保、リトライ設定のカスタマイズ、モニタリング戦略の実装が重要です。また、他のGCPサービスと組み合わせることで、より強力な非同期処理ソリューションを構築することができます。