Esse método é aplicável apenas a workers que estejam sendo executados em um serviço no ambiente padrão.
Ao usar filas pull, você é responsável pelo escalonamento dos workers com base no volume de processamento.
Como colocar tarefas em lease
Depois que as tarefas estiverem na fila, um worker poderá colocar uma ou mais delas em lease usando o método taskqueue.Lease. Pode haver um pequeno atraso até que as tarefas adicionadas recentemente usando taskqueue.Add sejam disponibilizadas por taskqueue.Lease.
Ao solicitar um lease, você especifica o número de tarefas a serem alocadas (máximo de 1.000) e a duração do lease em segundos (no máximo uma semana). A duração do lease deve ser longa o suficiente para garantir que haja tempo suficiente para a conclusão da tarefa mais lenta antes do fim do período de lease. É possível modificar um lease de tarefa usando taskqueue.ModifyLease.
Uma tarefa em lease fica indisponível para processamento por outro worker até que o lease expire.
O exemplo de código a seguir aloca 100 tarefas da fila pull-queue por uma hora:
Nem todas as tarefas são iguais. Seu código pode marcar tarefas com tags e depois escolher as que serão colocadas em lease por tag. A tag funciona como um filtro. Com este exemplo de código, é possível marcar tarefas e, em seguida, alocar por tags:
_,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,"")
Como regular taxas de pesquisa
Os workers que pesquisam a fila em busca de tarefas para alocar precisam detectar se estão tentando alocar tarefas mais rapidamente do que a fila pode fornecer. Se essa falha ocorrer, um erro de retirada será retornado de taskqueue.Lease.
Seu código precisará gerenciar esses erros, desativar a chamada de taskqueue.Lease e tentar novamente depois. Para evitar esse problema, defina um prazo maior de RPC ao chamar taskqueue.Lease e não insista quando uma solicitação de alocação retornar uma lista vazia de tarefas.
Se você gerar mais de 10 solicitações de LeaseTasks por fila por segundo, apenas as 10 primeiras solicitações retornarão resultados. Se as solicitações ultrapassarem esse limite, OK será retornado sem nenhum resultado.
Como monitorar tarefas no console do Google Cloud
Para ver informações sobre todas as tarefas e filas no aplicativo:
Abra a página Cloud Tasks no Google Cloud console e procure o valor Pull na coluna Tipo.
Clique no nome da fila em que você está interessado e abra a página de detalhes dela. Serão exibidas todas as tarefas na fila selecionada.
Como excluir tarefas
Depois que o worker conclui uma tarefa, ele precisa excluí-la da fila. Se continuarem sendo exibidas tarefas restantes em uma fila depois que o worker terminar de processá-las, é provável que tenha ocorrido falha no worker. Nesse caso, as tarefas serão processadas por outro worker.
É possível excluir uma lista de tarefas, como a retornada por taskqueue.Lease, passando-a para 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 entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 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\")"]]