Go 1.11 ha raggiunto la fine del supporto
e verrà ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment delle applicazioni Go 1.11, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment dei runtime legacy. Le tue applicazioni Go
1.11 continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti
consigliamo di eseguire la migrazione all'ultima versione supportata di Go.
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Una volta che le attività si trovano in una coda in modalità pull, un worker può prenderle in leasing. Una volta elaborate le attività,
il lavoratore deve eliminarle.
Crea attività e aggiungile alla coda in modalità pull.
Contesto importante
Questo metodo è applicabile solo ai worker in esecuzione all'interno di un servizio nell'ambiente standard.
Quando utilizzi le code pull, sei responsabile del dimensionamento dei worker in base al volume di elaborazione.
Leasing delle attività
Una volta che le attività sono in coda, un lavoratore può prenderne in affitto una o più utilizzando il metodo taskqueue.Lease. Potrebbe verificarsi un breve ritardo prima che le attività aggiunte di recente utilizzando taskqueue.Add diventino disponibili tramite taskqueue.Lease.
Quando richiedi un lease, specifichi il numero di attività da acquisire (fino a un massimo di 1000) e la durata del lease in secondi (fino a un massimo di una settimana). La durata del lease deve essere sufficiente a garantire che l'attività più lenta abbia il tempo di terminare prima della scadenza del periodo di lease. Puoi modificare una concessione di attività utilizzando taskqueue.ModifyLease.
Il leasing di un'attività la rende non disponibile per l'elaborazione da parte di un altro worker e rimane non disponibile fino alla scadenza del leasing.
Il seguente esempio di codice acquisisce 100 attività dalla coda pull-queue per un'ora:
Non tutte le attività sono uguali: il codice può "taggare" le attività e poi scegliere quelle da affittare in base al tag. Il tag funge da filtro. Il seguente esempio di codice mostra come taggare le attività e poi eseguire il lease in base ai tag:
_,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,"")
Regolazione dei tassi di polling
I worker che eseguono il polling della coda per le attività da acquisire devono rilevare se stanno tentando di acquisire attività più velocemente di quanto la coda possa fornirle. Se si verifica questo errore, taskqueue.Lease restituirà un errore di backoff.
Il tuo codice deve gestire questi errori, interrompere la chiamata a taskqueue.Lease e riprovare in un secondo momento. Per evitare questo problema, ti consigliamo di impostare una scadenza RPC più elevata quando chiami taskqueue.Lease. Devi anche eseguire il backoff quando una richiesta di lease restituisce un elenco vuoto di attività.
Se generi più di 10 richieste LeaseTasks per coda al secondo, solo le prime 10 richieste restituiranno risultati. Se le richieste superano questo limite, viene restituito OK con zero risultati.
Monitoraggio delle attività nella console Google Cloud
Per visualizzare informazioni su tutte le attività e le code nella tua applicazione:
Apri la pagina Cloud Tasks nella console Google Cloud e cerca il valore Pull nella colonna Tipo.
Fai clic sul nome della coda che ti interessa per aprire la pagina dei dettagli. Mostra tutte le attività nella coda selezionata.
Eliminazione delle attività
Una volta completata un'attività, il worker deve eliminarla dalla coda. Se vedi attività rimanenti in una coda dopo che un worker ha terminato di elaborarle, è probabile che il worker non sia riuscito a completarle. In questo caso, le attività verranno elaborate da un altro worker.
Puoi eliminare un elenco di attività, ad esempio quello restituito da taskqueue.Lease, passandolo a taskqueue.DeleteMulti:
tasks,err=taskqueue.Lease(ctx,100,"pull-queue",3600)// Perform some work with the tasks heretaskqueue.DeleteMulti(ctx,tasks,"pull-queue")
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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\")"]]