Go 1.11 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Go 1.11 アプリケーションをデプロイできなくなります。既存の Go 1.11 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Go に移行することをおすすめします。
push タスクの作成
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
このページでは、タスクを作成して push キューに配置する方法を説明します。タスクを処理する場合は、新しいタスク オブジェクトを作成してキューに配置する必要があります。タスクを処理するサービスとハンドラを明示的に指定し、必要に応じてタスク固有のデータをハンドラに渡すこともできます。また、タスクを実行するタイミングのスケジューリング、タスクが失敗した場合の再試行回数の制限など、タスクの構成を微調整することもできます。
新しいタスクを作成する
タスクを作成してキューに追加するには、taskqueue.Add 関数を呼び出します。
import("google.golang.org/appengine/taskqueue")
ワーカー サービスを指定する
タスクがキューから取り出される(ポップ)と、タスクはタスクキュー サービスによってワーカー サービスに送信されます。いずれのタスクにもターゲットと url があり、どのサービスとハンドラがそのタスクを実行するかがこれらによって決まります。
target
ターゲットは、どのサービスがタスク実行の HTTP リクエストを受け取るかを指定します。これは文字列であり、サービス / バージョン / インスタンスを正規形式のいずれかで指定します。よく使用される形式は次のとおりです。
service
version.service
instance.version.service
ターゲット文字列の前には、アプリのドメイン名が付加されます。タスクのターゲットを設定するには、次の 3 つの方法があります。
タスクを作成するときにターゲットを宣言します。
Task オブジェクトの作成時にターゲットを明示的に設定するには、Host
ヘッダーを設定します。
queue.yaml
でキューを定義するときに、target
ディレクティブを指定します(queue-blue
の定義をご覧ください)。target
が指定されているキューに追加されるタスクはすべて、そのターゲットを使用します。タスクの作成時に別のターゲットが割り当てられていても無視されます。
上記の 2 つの方法のいずれかでターゲットが指定されていない場合、タスクをキューに追加したサービスのバージョンが、そのタスクのターゲットになります。この方法でタスクをデフォルトのサービスとバージョンからキューに追加した場合、タスクの実行前にデフォルトのバージョンが変更されると、タスクは変更後のデフォルトのバージョンで実行されます。
url
url
に基づいて、ターゲット サービスのハンドラのうち 1 つが選択され、そのハンドラによってタスクが実行されます。
url
は、ターゲット サービス内のハンドラ URL パターンのうち 1 つに一致する必要があります。タスクに指定されたメソッドが GET
または PULL
である場合は、url
にクエリ パラメータを含めることができます。url
が指定されていない場合は、デフォルトの URL /_ah/queue/[QUEUE_NAME]
が使用されます。ここで [QUEUE_NAME]
はタスクのキューの名前です。
データをハンドラに渡す
データをハンドラに渡す場合、タスクの URL 内のクエリ パラメータとして渡す方法がありますが、この方法が可能なのはタスクで指定されているメソッドが GET
か PULL
の場合のみです。
NewPOSTTask
関数には query_data の位置引数が含まれています。データは通常、Key-Value ペアの辞書です。タスクのメソッドが POST
または PUT
の場合、データは HTTP リクエストのペイロードに追加されます。メソッドが GET
の場合は、URL にクエリ パラメータとして追加されます。
タスクに名前を付ける
新しいタスクを作成すると、デフォルトではタスクに一意の名前が割り当てられます。ただし、name
パラメータを使用すると、タスクに独自の名前を割り当てることができます。独自のタスク名を割り当てることの利点は、名前付きのタスクでは重複が除外されることです。つまり、タスク名を使用すると、タスクが 1 回のみ追加されることを保証できます。重複の除外は、タスクが完了するか、削除されてから 9 日間続きます。
重複除外ロジックはパフォーマンスのオーバーヘッドを大幅に増加させるため、レイテンシが増加し、場合によっては名前付きタスクに伴うエラー率が高まるので注意してください。このようなコストは、タイムスタンプのように連続したタスク名が付けられている場合、大幅に増大する可能性があります。そのため、独自の名前を割り当てる場合は、コンテンツのハッシュなどの適度に分散された接頭辞をタスク名に使用することをおすすめします。
独自の名前をタスクに割り当てる場合、名前の最大長が 500 文字で、名前には英字の大文字と小文字、数字、アンダースコア、ハイフンを使用できることに注意してください。
Cloud Datastore トランザクションの中でタスクをキューに追加する
タスクを Datastore トランザクションの一部としてキューに登録できます。これにより、トランザクションが正常に commit された場合にのみ、タスクがキューに登録されるようになります(キューへの登録が保証されます)。トランザクションの中で追加されたタスクは、そのトランザクションの一部とみなされ、同じレベルの分離と整合性を持つことになります。
1 つのトランザクションの中でタスクキューに挿入できるトランザクション タスクは 5 個までです。トランザクション タスクの名前をユーザーが指定することはできません。
次のコードサンプルでは、Datastore トランザクションの一部としてトランザクション タスクを push キューに挿入する方法を示します。
ワーカー サービスの代わりに遅延パッケージを使用する
上記のセクションで説明したように、実行するタスクごとに別個にハンドラを設定すると、タスクの複雑な引数のシリアル化 / シリアル化解除と同様、煩雑になる場合があります。特に、キューで実行するタスクが小さく、多種多様で数も多い場合には、厄介です。Go SDK に含まれるパッケージ(appengine/delay
)を使用すると、単純な API をエクスポーズするだけで、専用のタスクハンドラの設定やパラメータのシリアル化 / シリアル化解除の作業をすべて回避できます。
delay
パッケージを使用するには:
delay
パッケージは関数呼び出しとその引数をシリアル化して、タスクキューに追加します。タスクの実行時に、delay
パッケージで関数が実行されます。
delay
パッケージの使用方法については、該当のドキュメントをご覧ください。
マルチテナント アプリケーションでタスクを扱う
デフォルトでは、push キューで使用される名前空間は、タスク作成時点で名前空間マネージャーで設定されていた名前空間です。アプリケーションでマルチテナントを使用する場合は、名前空間 Go 1.11 API をご覧ください。
次のステップ
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-09-04 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-04 UTC。"],[[["\u003cp\u003eThis document details how to create new tasks and add them to push queues for processing by specifying a target service and handler.\u003c/p\u003e\n"],["\u003cp\u003eYou can customize task behavior by setting the target service, URL, and data payload for the worker service that will execute the task.\u003c/p\u003e\n"],["\u003cp\u003eTasks can be named for de-duplication purposes, but it's advised to use well-distributed prefixes for custom task names to avoid performance issues.\u003c/p\u003e\n"],["\u003cp\u003eTasks can be enqueued as part of a Datastore transaction, ensuring they are only added if the transaction is successfully committed and guaranteeing consistency.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003edelay\u003c/code\u003e package offers a simpler alternative to setting up dedicated task handlers by allowing direct serialization and execution of function calls.\u003c/p\u003e\n"]]],[],null,["# Creating Push Tasks\n\nThis page describes how to create tasks and place them in push queues. When you\nwant to process a task, you must create a new task object and place it on a\nqueue. You can explicitly specify the service and handler that process the task,\nand optionally pass task-specific data along to the handler. You can also\nfine-tune the configuration for the task, like scheduling a time in the future\nwhen it should be executed or limiting the number of times you want the task to\nbe retried if it fails.\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-differences) to learn about your migration options for legacy bundled services.\n\nCreating a new task\n-------------------\n\nTo create and enqueue a task, call the [taskqueue.Add](/appengine/docs/legacy/standard/go111/taskqueue/reference#Add) function. \n\n import(\"google.golang.org/appengine/taskqueue\")\n\nSpecifying the worker service\n-----------------------------\n\nWhen a task is popped off its queue, the Task Queue service sends it on\nto a worker service. Every task has a *target* and a *url*, which determine\nwhat service and handler will ultimately perform the task.\n\n### `target`\n\nThe target specifies the service that will receive the HTTP request to\nperform the task. It is a string that specifies a service/version/instance in\nany one of the [canonical forms](/appengine/docs/legacy/standard/go111/how-requests-are-routed#routing_via_url). The most often-used forms are: \n\n service\n version.service\n instance.version.service\n\nThe target string is prepended to the domain name of your app. There are three\nways to set the target for a task:\n\n- Declare the target when you construct the task.\n\n\n You can set the target explicitly when creating the [Task](/appengine/docs/legacy/standard/go111/taskqueue/reference#Task) object by setting\n the `Host` header:\n\n\n h := http.Header{}\n h.Add(\"Host\", \"versionHostname\")\n task := taskqueue.Task{\n \tHeader: h,\n }\n\n \u003cbr /\u003e\n\n- Include a `target` directive when you define a queue in the\n `queue.yaml`, as in the [definition](/appengine/docs/legacy/standard/go111/taskqueue/push/creating-push-queues) of `queue-blue`.\n All tasks added to a queue with a `target` will use that target, even if\n a different target was assigned to the task at construction time.\n\n- If no target is specified according to either of the previous two methods,\n then the task's target is the version of the service that enqueues it.\n Note that if you enqueue a task from the default service and version in\n this manner, and the default version changes before the task executes, it\n will run in the new default version.\n\n### `url`\n\nThe `url` selects one of the handlers in the target service, which will\nperform the task.\n\nThe `url` should match one of the handler URL patterns in the target\nservice. The `url` can include query parameters if the method specified in the task is\n`GET` or `PULL`. If no `url` is specified the default URL\n`/_ah/queue/[QUEUE_NAME]` is used, where `[QUEUE_NAME]` is the name of\nthe task's queue.\n\nPassing data to the handler\n---------------------------\n\nYou can pass data to the handler as query parameters in the task's URL, but\nonly if the method specified in the task is `GET` or `PULL`.\n\nThe [`NewPOSTTask`](/appengine/docs/legacy/standard/go111/taskqueue/reference#NewPOSTTask)\nfunction has a positional argument for query_data. The data is usually a\ndictionary of key-value pairs. If the task's method is `POST` or `PUT`, the data\nis added to the payload of the HTTP request. If the method is `GET` it is added\nto the URL as query parameters.\n\nNaming a task\n-------------\n\nWhen you create a new task, App Engine assigns the task a unique name by\ndefault. However, you can assign your own name to a task by using the `name`\nparameter. An advantage of assigning your own task names is that named tasks are\nde-duplicated, which means you can use task names to\nguarantee\nthat a task is only added once. De-duplication continues for 9 days after the\ntask is completed or deleted.\n\nNote that de-duplication logic introduces significant performance overhead,\nresulting in increased latencies and potentially increased error rates\nassociated with named tasks. These costs can be magnified significantly if task\nnames are sequential, such as with timestamps. So, if you assign your own names,\nwe recommend using a well-distributed prefix for task names, such as a hash of\nthe contents.\n\nIf you assign your own names to tasks, note that the maximum name length is 500\ncharacters, and the name can contain uppercase and lowercase letters, numbers\nunderscores, and hyphens.\n\nEnqueuing tasks in Cloud Datastore transactions\n-----------------------------------------------\n\nYou can enqueue a task as part of a Datastore transaction, such\nthat the task is only enqueued---and guaranteed to be enqueued---if the transaction\nis committed successfully. Tasks added in a\n[transaction](/appengine/docs/legacy/standard/go111/datastore/transactions) are\nconsidered to be a part of it and have the same level of\n[isolation and consistency](/appengine/docs/legacy/standard/go111/datastore/transactions#isolation_and_consistency).\n\nAn application cannot insert more than five transactional tasks into\n[task queues](/appengine/docs/legacy/standard/go111/taskqueue) during a single\ntransaction. Transactional tasks must not have user-specified names.\n\nThe following code sample demonstrates how to insert transactional tasks into a\npush queue as part of a Datastore transaction: \n\n import (\n \t\"net/url\"\n\n \t\"golang.org/x/net/context\"\n\n \t\"google.golang.org/appengine/datastore\"\n \t\"google.golang.org/appengine/taskqueue\"\n )\n\n func f(ctx context.Context) {\n \terr := datastore.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/datastore.html#google_golang_org_appengine_datastore_RunInTransaction(ctx, func(ctx context.Context) error {\n \t\tt := taskqueue.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/taskqueue.html#google_golang_org_appengine_taskqueue_Task_NewPOSTTask(\"/worker\", url.Values{\n \t\t\t// ...\n \t\t})\n \t\t// Use the transaction's context when invoking taskqueue.Add.\n \t\t_, err := taskqueue.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/taskqueue.html#google_golang_org_appengine_taskqueue_Task_Add(ctx, t, \"\")\n \t\tif err != nil {\n \t\t\t// Handle error\n \t\t}\n \t\t// ...\n \t\treturn nil\n \t}, nil)\n \tif err != nil {\n \t\t// Handle error\n \t}\n \t// ...\n }\n\nUsing the delayed package instead of a worker service\n-----------------------------------------------------\n\nSetting up a handler for each distinct task (as described in the previous\nsections) can be cumbersome, as can serializing and deserializing complex\narguments for the task---particularly if you have many diverse but small tasks\nthat you want to run on the queue. The Go SDK includes a package\n(`appengine/delay`) exposing a simple API that allows you to bypass all the work\nof setting up dedicated task handlers and serializing and deserializing your\nparameters.\n\nTo use the `delay` package: \n\n var expensiveFunc = delay.Func(\"some-arbitrary-key\", func(ctx context.Context, a string, b int) {\n \t// do something expensive!\n })\n\n // Somewhere else\n expensiveFunc.Call(ctx, \"Hello, world!\", 42)\n\nThe `delay` package serializes your function call and its arguments, then adds\nit to the task queue. When the task is executed, the `delay` package executes\nthe function.\n\nFor more information about using the `delay` package, refer to\n[its documentation](/appengine/docs/legacy/standard/go111/taskqueue/delay).\n\nWorking with tasks in a multi-tenant application\n------------------------------------------------\n\nBy default, push queues use the current namespace as set in the namespace\nmanager at the time the task is created. If your application uses multitenancy,\nsee the [Namespaces Go 1.11 API](/appengine/docs/legacy/standard/go111/multitenancy/multitenancy#Using_namespaces_with_the_Task_Queue).\n\nWhat's next\n-----------\n\n- Learn how to [create task\n handlers](/appengine/docs/legacy/standard/go111/taskqueue/push/creating-handlers)."]]