Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Programar e executar um cron job usando a CLI gcloud
Neste guia de início rápido, mostramos como usar a CLI gcloud para realizar algumas operações básicas com o Cloud Scheduler.
Neste guia de início rápido, você fará as seguintes tarefas:
Crie um tópico do Pub/Sub para configurar como destino do job do Cloud Scheduler.
Crie um cron job usando o Cloud Scheduler e configure uma programação recorrente para ele.
Execute o job.
Verificar se o job foi concluído com sucesso.
O Cloud Scheduler tem um nível gratuito. Não convém executar este guia de início rápido.
gerar custos. Para mais informações, consulte Preços.
Antes de começar
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
Um tópico do Pub/Sub é um recurso em que os editores podem enviar mensagens.
Para receber as mensagens publicadas em um tópico, você precisa criar uma inscrição nele.
Configure um tópico do Pub/Sub para usar como destino do cron job:
gcloudpubsubtopicscreatecron-topic
Isso criará um tópico chamado cron-topic.
Para receber mensagens e ver os resultados do job, crie uma
assinatura do Pub/Sub:
Use o comando gcloud scheduler jobs create pubsub
para configurar uma unidade de trabalho conhecida como cron job, que é enviada a um
destino do Pub/Sub em uma programação recorrente. A programação é especificada
usando um formato baseado em unix-cron. Para mais informações, consulte
Formato de cron job e fuso horário.
[[["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-08-18 UTC."],[],[],null,["# Quickstart: Schedule and run a cron job using the Google Cloud CLI\n\nSchedule and run a cron job using the gcloud CLI\n================================================\n\nThis quickstart shows you how to use the gcloud CLI to perform some\nbasic operations using Cloud Scheduler.\n\nIn this quickstart, you:\n\n1. Create a Pub/Sub topic to set up as your Cloud Scheduler job target.\n2. Create a cron job using Cloud Scheduler, and configure a recurring schedule for the job.\n3. Run your job.\n4. Verify that the job has run successfully.\n\nCloud Scheduler has a free tier and running this quickstart shouldn't\nincur any costs. For more information, see [Pricing](/scheduler/pricing).\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n- [Create or select a Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n - Create a Google Cloud project:\n\n ```\n gcloud projects create PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with a name for the Google Cloud project you are creating.\n - Select the Google Cloud project that you created:\n\n ```\n gcloud config set project PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your Google Cloud project name.\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Scheduler, Pub/Sub APIs:\n\n\n ```bash\n gcloud services enable cloudscheduler.googleapis.com pubsub.googleapis.com\n ```\n\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n- [Create or select a Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n - Create a Google Cloud project:\n\n ```\n gcloud projects create PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with a name for the Google Cloud project you are creating.\n - Select the Google Cloud project that you created:\n\n ```\n gcloud config set project PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your Google Cloud project name.\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Scheduler, Pub/Sub APIs:\n\n\n ```bash\n gcloud services enable cloudscheduler.googleapis.com pubsub.googleapis.com\n ```\n\n\u003cbr /\u003e\n\nCreate a Pub/Sub topic and subscription\n---------------------------------------\n\nA Pub/Sub topic is a resource to which publishers can send messages.\nTo receive messages published to a topic, you must create a subscription to\nthat topic.\n\n1. Set up a Pub/Sub topic to use as a target for your cron job:\n\n gcloud pubsub topics create cron-topic\n\n This creates a topic called `cron-topic`.\n2. To receive messages and view the results of your job, create a\n Pub/Sub subscription:\n\n gcloud pubsub subscriptions create cron-sub --topic cron-topic\n\nCreate a cron job using Cloud Scheduler\n---------------------------------------\n\nUse the [`gcloud scheduler jobs create pubsub`](/sdk/gcloud/reference/scheduler/jobs/create/pubsub)\ncommand to set up a unit of work known as a *cron job* that is sent to a\nPub/Sub target on a recurring schedule. The schedule is specified\nusing a format based on unix-cron. For more information, see\n[Cron job format and time zone](/scheduler/docs/configuring/cron-job-schedules). \n\n gcloud scheduler jobs create pubsub my-cron-job \\\n --schedule=\"30 16 * * 7\" \\\n --topic=cron-topic \\\n --location=\"us-central1\" \\\n --message-body=\"Hello world\"\n\nYou've created a job that sends a \"Hello world\" message to your Pub/Sub\ntopic at 16:30 on Sundays.\n\nYou can now run the job.\n\nRun your job\n------------\n\nIn addition to executing according to its specified schedule, you can force your\njob to run immediately: \n\n gcloud scheduler jobs run my-cron-job --location=\"us-central1\"\n\nNote that due to some initial configuration, the first job created in a\nproject can take a few minutes to run.\n\nNext, you can verify that your Pub/Sub topic received the message.\n\nVerify the results in Pub/Sub\n-----------------------------\n\nVerify that your Pub/Sub topic is receiving messages from your job.\n\n1. Pull Pub/Sub messages from a subscription:\n\n gcloud pubsub subscriptions pull cron-sub --limit 5\n\n If there are no messages pulled initially, run the command again.\n2. View the results of running your job. The output should look similar to the\n following:\n\n DATA: Hello world!\n MESSAGE_ID: 5028933846601543\n ORDERING_KEY:\n ATTRIBUTES:\n DELIVERY_ATTEMPT:\n ACK_ID: RFAGFixdRkhRNxkIaFEOT14jPzUgKEUQAgVPAihdeTFXLkFacGhRDRlyfWB9[...]\n\nClean up\n--------\n\n\nTo avoid incurring charges to your Google Cloud account for\nthe resources used on this page, delete the Google Cloud project with the\nresources.\n\n| **Caution** : Deleting a project has the following effects:\n|\n| - **Everything in the project is deleted.** If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.\n| - **Custom project IDs are lost.** When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an `appspot.com` URL, delete selected resources inside the project instead of deleting the whole project.\n|\n|\n| If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects\n| can help you avoid exceeding project quota limits.\n1. Delete a Google Cloud project: \n\n```\ngcloud projects delete PROJECT_ID\n```\n\n\u003cbr /\u003e\n\nAlternatively, delete the resources you created for this quickstart:\n\n1. Delete the cron job. In Cloud Shell or on the machine where you installed\n the gcloud CLI, run the command:\n\n gcloud scheduler jobs delete \u003cvar translate=\"no\"\u003eMY_JOB\u003c/var\u003e \\\n --location=\"\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e\"\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eMY_JOB\u003c/var\u003e: the name of the job to be deleted.\n - \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: the location of the job. By default, uses the location of the current project's App Engine app if there is an associated app.\n2. Delete the Pub/Sub topic. In Cloud Shell or on the\n machine where you installed the gcloud CLI, run the command:\n\n gcloud pubsub topics delete \u003cvar translate=\"no\"\u003eTOPIC_ID\u003c/var\u003e\n\n Replace \u003cvar translate=\"no\"\u003eTOPIC_ID\u003c/var\u003e with the ID of the\n Pub/Sub topic to be deleted.\n3. Delete the Pub/Sub subscription. In Cloud Shell or on\n the machine where you installed the gcloud CLI, run the command:\n\n gcloud pubsub subscriptions delete \u003cvar translate=\"no\"\u003eSUBSCRIPTION_ID\u003c/var\u003e\n\n Replace \u003cvar translate=\"no\"\u003eSUBSCRIPTION_ID\u003c/var\u003e with the ID of the\n Pub/Sub subscription to be deleted.\n\nWhat's next\n-----------\n\n- Learn more about [Cloud Scheduler](/scheduler/docs/overview)\n\n- Learn how to\n [view Cloud Scheduler logs](/scheduler/docs/viewing-logs)"]]