import("net/url""golang.org/x/net/context""google.golang.org/appengine/datastore""google.golang.org/appengine/taskqueue")funcf(ctxcontext.Context){err:=datastore.RunInTransaction(ctx,func(ctxcontext.Context)error{t:=taskqueue.NewPOSTTask("/worker",url.Values{// ...})// Use the transaction's context when invoking taskqueue.Add._,err:=taskqueue.Add(ctx,t,"")iferr!=nil{// Handle error}// ...returnnil},nil)iferr!=nil{// Handle error}// ...}
[[["容易理解","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 (世界標準時間)。"],[[["\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)."]]