Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Una vez que las tareas están en una lista de extracción, un trabajador puede asignarse tiempo para ellas. Después de procesar las tareas, el trabajador debe borrarlas.
Este método solo se aplica a trabajadores que se ejecutan dentro de un servicio del entorno estándar.
Cuando utilizas las listas de extracción, tienes la responsabilidad de escalar los trabajadores según el volumen de procesamiento.
Asignación de tiempo para tareas
Cuando las tareas se encuentran en la lista, se puede asignar tiempo a un trabajador para una o más de ellas con el método taskqueue.Lease. Puede llevar algo de tiempo que las tareas recién agregadas con taskqueue.Add estén disponibles mediante taskqueue.Lease.
Cuando solicitas una asignación, debes especificar la cantidad de tareas (hasta un máximo de 1,000) y la duración en segundos (hasta un máximo de una semana). La asignación debe durar lo suficiente para garantizar que la tarea más lenta tenga tiempo de completarse antes de que venza el período de la asignación. Puedes modificar la asignación de tiempo de una tarea mediante taskqueue.ModifyLease.
Cuando se asigna tiempo para una tarea, esta deja de estar disponible para que la procese otro trabajador hasta que venza la asignación.
En el ejemplo de código que sigue, se realiza una asignación de tiempo de una hora para 100 tareas de la lista pull-queue.
No todas las tareas son iguales. Tu código puede “etiquetar” tareas y después elegir para qué tareas asignar tiempo según la etiqueta. La etiqueta actúa como un filtro. El siguiente ejemplo de código demuestra cómo etiquetar tareas y luego arrendar según las etiquetas:
_,err=taskqueue.Add(ctx,&taskqueue.Task{Payload:[]byte("parse"),Method:"PULL",Tag:"parse",},"pull-queue")_,err=taskqueue.Add(ctx,&taskqueue.Task{Payload:[]byte("render"),Method:"PULL",Tag:"render",},"pull-queue")// leases render tasks, but not parsetasks,err=taskqueue.LeaseByTag(ctx,100,"pull-queue",3600,"render")// Leases up to 100 tasks that have same tag.// Tag is that of "oldest" task by ETA.tasks,err=taskqueue.LeaseByTag(ctx,100,"pull-queue",3600,"")
Regula tasas de sondeo
Los trabajadores que sondeen la lista en busca de tareas para las que puedan asignarse tiempo deberían detectar si están intentando asignarse tiempo para tareas más rápido de lo que la lista puede proporcionarlas. Si se produce este error, se mostrará un error de tiempo de espera en taskqueue.Lease.
El código debe manejar estos errores, dejar de llamar a taskqueue.Lease y volver a intentarlo más tarde. Para evitar este problema, considera establecer un plazo mayor de RPC cuando llames a taskqueue.Lease. También debes dejar de llamar si una solicitud de asignación muestra una lista vacía de tareas.
Si generas más de 10 solicitudes LeaseTasks por lista por segundo, solo las primeras 10 solicitudes mostrarán resultados. Si las solicitudes superan este límite, se muestra OK sin resultados.
Supervisa tareas en la Google Cloud consola
Para ver información sobre todas las tareas y las listas en tu aplicación, haz lo siguiente:
Abre la página Cloud Tasks en la Google Cloud consola y busca el valor Pull en la columna Type.
Haz clic en el nombre de la lista que te interesa y abre la página de detalles de la lista. Se muestran todas las tareas en la lista seleccionada.
Cómo borrar tareas
Una vez que un trabajador completa una tarea, debe borrarla de la lista. Si ves que las tareas permanecen en una cola después de que el trabajador termina de procesarlas, es probable que haya fallado; en ese caso, otro trabajador procesará las tareas.
Para borrar una lista de tareas, como la que muestra taskqueue.Lease, pásala a taskqueue.DeleteMulti:
tasks,err=taskqueue.Lease(ctx,100,"pull-queue",3600)// Perform some work with the tasks heretaskqueue.DeleteMulti(ctx,tasks,"pull-queue")
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eWorkers can lease tasks from a pull queue, which temporarily makes them unavailable to other workers for processing, until the lease expires.\u003c/p\u003e\n"],["\u003cp\u003eAfter processing, the worker must delete the task from the queue to ensure it's not processed again.\u003c/p\u003e\n"],["\u003cp\u003eTasks can be tagged, allowing workers to lease specific tasks based on their tag using the \u003ccode\u003eLeaseByTag\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eWhen polling for tasks, workers should handle back-off errors returned from \u003ccode\u003etaskqueue.Lease\u003c/code\u003e and avoid exceeding 10 LeaseTasks requests per queue per second, to prevent issues with task availability.\u003c/p\u003e\n"],["\u003cp\u003eThe task queue API discussed is supported for first-generation runtimes, and the page provides information on upgrading to corresponding second-generation runtimes.\u003c/p\u003e\n"]]],[],null,["# Leasing Pull Tasks\n\nOnce tasks are in a pull queue, a worker can lease them. After the tasks are processed\nthe worker must delete them.\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\nBefore you begin\n----------------\n\n- Create a [pull queue](/appengine/docs/legacy/standard/go111/taskqueue/pull/creating-pull-queues).\n- [Create tasks](/appengine/docs/legacy/standard/go111/taskqueue/pull/creating-tasks) and add them to the pull queue.\n\nImportant context\n-----------------\n\n- This method is only applicable to workers that are running within a service in the standard environment.\n- When you use pull queues, you are responsible for scaling your workers based on your processing volume.\n\nLeasing tasks\n-------------\n\nAfter the tasks are in the queue, a worker can lease one or more of them using the [`taskqueue.Lease`](/appengine/docs/legacy/standard/go111/taskqueue/reference#Lease) method. There may be a short delay before tasks recently added using [`taskqueue.Add`](/appengine/docs/legacy/standard/go111/taskqueue/reference#Add) become available via [`taskqueue.Lease`](/appengine/docs/legacy/standard/go111/taskqueue/reference#Lease).\n\nWhen you request a lease, you specify the number of tasks to lease (up to a maximum of 1,000 tasks) and the duration of the lease in seconds (up to a maximum of one week). The lease duration needs to be long enough to ensure that the slowest task will have time to finish before the lease period expires. You can modify a task lease using [`taskqueue.ModifyLease`](/appengine/docs/legacy/standard/go111/taskqueue/reference#ModifyLease).\n\nLeasing a task makes it unavailable for processing by another worker, and it remains unavailable until the lease expires.\n| **Note:** `taskqueue.Lease` operates only on pull queues. If you attempt to lease tasks added in a push queue, App Engine returns an error.\n\nThe following code sample leases 100 tasks from the queue `pull-queue` for one hour: \n\n tasks, err := taskqueue.Lease(ctx, 100, \"pull-queue\", 3600)\n\n### Batching with task tags\n\n|\n| **Beta**\n|\n|\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nNot all tasks are alike; your code can \"tag\" tasks and then choose tasks to lease by tag. The tag acts as a filter. The following code sample demonstrates how to tag tasks and then lease by tags: \n\n _, err = taskqueue.Add(ctx, &taskqueue.Task{\n \tPayload: []byte(\"parse\"), Method: \"PULL\", Tag: \"parse\",\n }, \"pull-queue\")\n _, err = taskqueue.Add(ctx, &taskqueue.Task{\n \tPayload: []byte(\"render\"), Method: \"PULL\", Tag: \"render\",\n }, \"pull-queue\")\n\n // leases render tasks, but not parse\n tasks, err = taskqueue.LeaseByTag(ctx, 100, \"pull-queue\", 3600, \"render\")\n\n // Leases up to 100 tasks that have same tag.\n // Tag is that of \"oldest\" task by ETA.\n tasks, err = taskqueue.LeaseByTag(ctx, 100, \"pull-queue\", 3600, \"\")\n\n### Regulating polling rates\n\nWorkers that poll the queue for tasks to lease should detect whether they are attempting to lease tasks faster than the queue can supply them. If this failure occurs, a back-off error will be returned from `taskqueue.Lease`. \n\nYour code must handle these errors, back off from calling `taskqueue.Lease`, and then try again later. To avoid this problem, consider setting a higher RPC deadline when calling `taskqueue.Lease`. You should also back off when a lease request returns an empty list of tasks.\nIf you generate more than 10 LeaseTasks requests per queue per second, only the first 10 requests will return results. If requests exceed this limit, `OK` is returned with zero results.\n\n\nMonitoring tasks in the Google Cloud console\n--------------------------------------------\n\nTo view information about all the tasks and queues in your application:\n\n1. Open the **Cloud Tasks** page in the Google Cloud console and look for the *Pull* value in column **Type**.\n\n [Go to Cloud Tasks](https://console.cloud.google.com/cloudtasks)\n2. Click on the name of the queue in which you are interested, opening the queue details page. It displays all of the tasks in the selected queue.\n\nDeleting tasks\n--------------\n\nOnce a worker completes a task, it needs to delete the task from the queue. If you see tasks remaining in a queue after a worker finishes processing them, it is likely that the worker failed; in this case, the tasks will be processed by another worker.\n\nYou can delete a list of tasks, such as that returned by `taskqueue.Lease`, by passing it to [`taskqueue.DeleteMulti`](/appengine/docs/legacy/standard/go111/taskqueue/reference#DeleteMulti): \n\n tasks, err = taskqueue.Lease(ctx, 100, \"pull-queue\", 3600)\n // Perform some work with the tasks here\n\n taskqueue.DeleteMulti(ctx, tasks, \"pull-queue\")"]]