사용 흐름

일괄 처리를 사용하는 단계는 다음과 같습니다.

새 일괄 작업 만들기

BatchJob 리소스를 만들려면 MutateBatchJob를 호출합니다. BatchJob 객체를 구성할 때 선택적으로 metadata.execution_limit_seconds를 양의 정수로 설정하여 작업이 자동으로 취소되기 전에 실행될 수 있는 대략적인 상한(초)을 구성할 수 있습니다(추가 사용 안내 참조).

자바

private String createBatchJob(BatchJobServiceClient batchJobServiceClient, long customerId) {
  BatchJobOperation operation =
      BatchJobOperation.newBuilder().setCreate(BatchJob.newBuilder().build()).build();
  String batchJobResourceName =
      batchJobServiceClient
          .mutateBatchJob(Long.toString(customerId), operation)
          .getResult()
          .getResourceName();
  System.out.printf("Created a mutate job with resource name: '%s'.%n", batchJobResourceName);

  return batchJobResourceName;
}
      

C#

private static string CreateBatchJob(BatchJobServiceClient batchJobService,
    long customerId)
{
    BatchJobOperation operation = new BatchJobOperation()
    {
        Create = new BatchJob()
        {
        }
    };
    string batchJobResourceName =
        batchJobService.MutateBatchJob(customerId.ToString(), operation)
        .Result.ResourceName;
    Console.WriteLine($"Created a batch job with resource name: " +
        $"'{batchJobResourceName}'.");

    return batchJobResourceName;
}
      

PHP

private static function createBatchJob(
    BatchJobServiceClient $batchJobServiceClient,
    int $customerId
): string {
    // Creates a batch job operation to create a new batch job.
    $batchJobOperation = new BatchJobOperation();
    $batchJobOperation->setCreate(new BatchJob());

    // Issues a request to the API and get the batch job's resource name.
    $batchJobResourceName = $batchJobServiceClient->mutateBatchJob(
        MutateBatchJobRequest::build($customerId, $batchJobOperation)
    )->getResult()->getResourceName();
    printf(
        "Created a batch job with resource name: '%s'.%s",
        $batchJobResourceName,
        PHP_EOL
    );
    return $batchJobResourceName;
}
      

Python

def create_batch_job(
    batch_job_service: BatchJobServiceClient,
    customer_id: str,
    batch_job_operation: BatchJobOperation,
) -> str:
    """Creates a batch job for the specified customer ID.

    Args:
        batch_job_service: an instance of the BatchJobService message class.
        customer_id: a str of a customer ID.
        batch_job_operation: a BatchJobOperation instance set to "create"

    Returns: a str of a resource name for a batch job.
    """
    try:
        response: MutateBatchJobResponse = batch_job_service.mutate_batch_job(
            customer_id=customer_id, operation=batch_job_operation
        )
        resource_name: str = response.result.resource_name
        print(f'Created a batch job with resource name "{resource_name}"')
        return resource_name
    except GoogleAdsException as exception:
        handle_googleads_exception(exception)
        # This line will likely not be reached due to sys.exit(1) in handle_googleads_exception
        # but to satisfy the type checker, we add a return statement.
        return ""  # Or raise an exception
      

Ruby

def create_batch_job(client, batch_job_service, customer_id)
  # Creates a batch job operation to create a new batch job.
  operation = client.operation.create_resource.batch_job

  # Issues a request to the API and get the batch job's resource name.
  response = batch_job_service.mutate_batch_job(
    customer_id: customer_id,
    operation: operation
  )

  batch_job_resource_name = response.result.resource_name
  puts "Created a batch job with resource name: '#{batch_job_resource_name}'"

  batch_job_resource_name
end
      

Perl

sub create_batch_job {
  my ($batch_job_service, $customer_id) = @_;

  # Create a batch job operation.
  my $batch_job_operation =
    Google::Ads::GoogleAds::V26::Services::BatchJobService::BatchJobOperation->
    new({create => Google::Ads::GoogleAds::V26::Resources::BatchJob->new({})});

  my $batch_job_resource_name = $batch_job_service->mutate({
      customerId => $customer_id,
      operation  => $batch_job_operation
    })->{result}{resourceName};

  printf
    "Created a batch job with resource name: '%s'.\n",
    $batch_job_resource_name;

  return $batch_job_resource_name;
}
      

curl

# Creates a batch job.
#
# Variables:
#   API_VERSION,
#   CUSTOMER_ID,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.

curl -f --request POST \
"https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/batchJobs:mutate" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data @- <<EOF
{
  "operation": {
    "create": {}
  }
}
EOF
      

프로세스의 이 시점에서 작업의 status은 PENDING입니다.

일괄 작업에 변형 작업 추가

AddBatchJobOperations를 호출하여 이전 단계에서 만든 일괄 작업에 하나 이상의 MutateOperation 객체를 추가합니다. 그러면 응답에 다음이 포함됩니다.

일괄 작업에 대한 첫 번째 AddBatchJobOperations 요청은 sequence_token를 생략해야 합니다. AddBatchJobOperations를 다시 호출하여 작업을 더 추가할 때는 이전에 가져온 시퀀스 토큰을 요청의 sequence_token 필드에 지정합니다. 빈 mutate_operations 목록으로 메서드를 호출하면 BatchJobError.EMPTY_OPERATIONS 오류가 반환되고, 이전에 가져온 시퀀스 토큰이 아닌 다른 시퀀스 토큰으로 호출하면 BatchJobError.INVALID_SEQUENCE_TOKEN 오류가 반환되며, 작업이 실행되기 시작한 후 작업을 추가하려고 하면 BatchJobError.CANNOT_MODIFY_JOB_AFTER_JOB_STARTS_RUNNING 오류가 반환됩니다.

일괄 작업의 status가 PENDING인 동안 sequence_token는 BatchJob 리소스에서 next_add_sequence_token로도 사용할 수 있으며 나중에 검색할 수 있습니다.

새 캠페인과 해당 광고 그룹, 광고, 키워드로 구성된 전체 캠페인과 같은 종속 객체를 만드는 경우 임시 ID를 사용하여 리소스 이름을 지정할 수 있습니다.

자바

private void addAllBatchJobOperations(
    BatchJobServiceClient batchJobServiceClient, long customerId, String batchJobResourceName) {
  AddBatchJobOperationsResponse response =
      batchJobServiceClient.addBatchJobOperations(
          AddBatchJobOperationsRequest.newBuilder()
              .setResourceName(batchJobResourceName)
              .addAllMutateOperations(buildAllOperations(customerId))
              .build());
  System.out.printf(
      "%d mutate operations have been added so far.%n", response.getTotalOperations());

  // You can use this next sequence token for calling addBatchJobOperations() next time.
  System.out.printf(
      "Next sequence token for adding next operations is '%s'.%n",
      response.getNextSequenceToken());
}
      

C#

private static void AddAllBatchJobOperations(BatchJobServiceClient batchJobService,
    long customerId, string batchJobResourceName)
{
    AddBatchJobOperationsResponse response =
        batchJobService.AddBatchJobOperations(
            new AddBatchJobOperationsRequest()
            {
                ResourceName = batchJobResourceName,
                MutateOperations = { BuildAllOperations(customerId) }
            });
    Console.WriteLine($"{response.TotalOperations} mutate operations have been added" +
        $" so far.");

    // You can use this next sequence token for calling AddBatchJobOperations() next time.
    Console.WriteLine($"Next sequence token for adding next operations is " +
        $"'{response.NextSequenceToken}'.");
}
      

PHP

private static function addAllBatchJobOperations(
    BatchJobServiceClient $batchJobServiceClient,
    int $customerId,
    string $batchJobResourceName
): void {
    $response = $batchJobServiceClient->addBatchJobOperations(
        AddBatchJobOperationsRequest::build(
            $batchJobResourceName,
            '',
            self::buildAllOperations($customerId)
        )
    );
    printf(
        "%d mutate operations have been added so far.%s",
        $response->getTotalOperations(),
        PHP_EOL
    );
    // You can use this next sequence token for calling addBatchJobOperations() next time.
    printf(
        "Next sequence token for adding next operations is '%s'.%s",
        $response->getNextSequenceToken(),
        PHP_EOL
    );
}
      

Python

def add_all_batch_job_operations(
    batch_job_service: BatchJobServiceClient,
    operations: List[MutateOperation],
    resource_name: str,
) -> None:
    """Adds all mutate operations to the batch job.

    As this is the first time for this batch job, we pass null as a sequence
    token. The response will contain the next sequence token that we can use
    to upload more operations in the future.

    Args:
        batch_job_service: an instance of the BatchJobService message class.
        operations: a list of a mutate operations.
        resource_name: a str of a resource name for a batch job.
    """
    try:
        response: AddBatchJobOperationsResponse = (
            batch_job_service.add_batch_job_operations(
                resource_name=resource_name,
                sequence_token=None,  # type: ignore
                mutate_operations=operations,
            )
        )

        print(
            f"{response.total_operations} mutate operations have been "
            "added so far."
        )

        # You can use this next sequence token for calling
        # add_batch_job_operations() next time.
        print(
            "Next sequence token for adding next operations is "
            f"{response.next_sequence_token}"
        )
    except GoogleAdsException as exception:
        handle_googleads_exception(exception)
      

Ruby

def add_all_batch_job_operations(
  client,
  batch_job_service,
  customer_id,
  batch_job_resource_name)
  response = batch_job_service.add_batch_job_operations(
    resource_name: batch_job_resource_name,
    mutate_operations: build_all_operations(client, customer_id),
  )
  puts "#{response.total_operations} mutate operations have been added so far."

  # You can use this next sequence token for calling
  # add_all_batch_job_operations() next time
  puts "Next sequence token for adding next operations is " \
    "'#{response.next_sequence_token}'"
end
      

Perl

sub add_all_batch_job_operations {
  my ($batch_job_service, $customer_id, $batch_job_resource_name) = @_;

  my $add_batch_job_operations_response = $batch_job_service->add_operations({
      resourceName     => $batch_job_resource_name,
      sequenceToken    => undef,
      mutateOperations => build_all_operations($customer_id)});

  printf
    "%d batch operations have been added so far.\n",
    $add_batch_job_operations_response->{totalOperations};

  # You can use this next sequence token for calling add_operations() next time.
  printf
    "Next sequence token for adding next operations is '%s'.\n",
    $add_batch_job_operations_response->{nextSequenceToken};
}
      

curl

# Adds operations to a batch job.
#
# Variables:
#   API_VERSION,
#   CUSTOMER_ID,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.
#   BATCH_JOB_RESOURCE_NAME:
#     The resource name of the batch job to which the operations should be added
#     as returned by the previous step.

curl -f --request POST \
"https://googleads.googleapis.com/v${API_VERSION}/${BATCH_JOB_RESOURCE_NAME}:addOperations" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data @- <<EOF
{
  "mutateOperations": [
    {
      "campaignBudgetOperation": {
        "create": {
          "resourceName": "customers/${CUSTOMER_ID}/campaignBudgets/-1",
          "name": "batch job budget #${RANDOM}",
          "deliveryMethod": "STANDARD",
          "amountMicros": 5000000
        }
      }
    },
    {
      "campaignOperation": {
        "create": {
          "advertisingChannelType": "SEARCH",
          "status": "PAUSED",
          "name": "batch job campaign #${RANDOM}",
          "campaignBudget": "customers/${CUSTOMER_ID}/campaignBudgets/-1",
          "resourceName": "customers/${CUSTOMER_ID}/campaigns/-2",
          "manualCpc": {
          }
        }
      },
    }
  ]
}
EOF
      

클라이언트 라이브러리의 GitHub에서 빌드 작업 함수의 콘텐츠를 보려면 클릭하세요.

일괄 작업 실행

모든 작업을 추가한 후 업로드된 작업에서 RunBatchJob를 호출하여 Google Ads API에 일괄 작업을 실행하도록 요청할 수 있습니다. 작업이 이미 실행되기 시작한 후에 RunBatchJob를 호출하면 BatchJobError.CANNOT_MODIFY_JOB_AFTER_JOB_STARTS_RUNNING 오류가 반환됩니다.

자바

private OperationFuture runBatchJob(
    BatchJobServiceClient batchJobServiceClient, String batchJobResourceName) {
  OperationFuture operationResponse =
      batchJobServiceClient.runBatchJobAsync(batchJobResourceName);

  // BEWARE! The above call returns an OperationFuture. The execution of that future depends on
  // the thread pool which is owned by batchJobServiceClient. If you use this future, you *must*
  // keep the service client in scope too.
  // See https://developers.google.com/google-ads/api/docs/client-libs/java/lro for more detail.

  System.out.printf(
      "Mutate job with resource name '%s' has been executed.%n", batchJobResourceName);

  return operationResponse;
}
      

C#

private Operation<Empty, BatchJobMetadata> RunBatchJob(
    BatchJobServiceClient batchJobService, string batchJobResourceName)
{
    Operation<Empty, BatchJobMetadata> operationResponse =
        batchJobService.RunBatchJob(batchJobResourceName);
    Console.WriteLine($"Batch job with resource name '{batchJobResourceName}' has been " +
        $"executed.");

    return operationResponse;
}
      

PHP

private static function runBatchJob(
    BatchJobServiceClient $batchJobServiceClient,
    string $batchJobResourceName
): OperationResponse {
    $operationResponse =
        $batchJobServiceClient->runBatchJob(RunBatchJobRequest::build($batchJobResourceName));
    printf(
        "Batch job with resource name '%s' has been executed.%s",
        $batchJobResourceName,
        PHP_EOL
    );
    return $operationResponse;
}
      

Python

def run_batch_job(
    batch_job_service: BatchJobServiceClient, resource_name: str
) -> Operation:
    """Runs the batch job for executing all uploaded mutate operations.

    Args:
        batch_job_service: an instance of the BatchJobService message class.
        resource_name: a str of a resource name for a batch job.

    Returns: a google.api_core.operation.Operation instance.
    """
    try:
        response: Operation = batch_job_service.run_batch_job(
            resource_name=resource_name
        )
        print(
            f'Batch job with resource name "{resource_name}" has been '
            "executed."
        )
        return response
    except GoogleAdsException as exception:
        handle_googleads_exception(exception)
        # This line will likely not be reached due to sys.exit(1) in handle_googleads_exception
        # but to satisfy the type checker, we add a return statement.
        # In a real application, you might want to return a dummy Operation or raise an error.
        return Operation(
            op_type_name="type.googleapis.com/google.protobuf.Empty",
            complete=True,
            done_callbacks=[],
            metadata_type=None,
            result_type=None,
        )  # type: ignore
      

Ruby

def run_batch_job(batch_job_service, batch_job_resource_name)
  operation_response = batch_job_service.run_batch_job(
    resource_name: batch_job_resource_name,
  )
  puts "Batch job with resource name '#{batch_job_resource_name}' " \
    "has been executed."
  operation_response
end
      

Perl

sub run_batch_job {
  my ($batch_job_service, $batch_job_resource_name) = @_;

  my $batch_job_lro =
    $batch_job_service->run({resourceName => $batch_job_resource_name});

  printf
    "Batch job with resource name '%s' has been executed.\n",
    $batch_job_resource_name;

  return $batch_job_lro;
}
      

curl

# Runs a batch job.
#
# Variables:
#   API_VERSION,
#   CUSTOMER_ID,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.
#   BATCH_JOB_RESOURCE_NAME:
#     The resource name of the batch job to run as returned by the previous step.

curl -f --request POST \
"https://googleads.googleapis.com/v${API_VERSION}/${BATCH_JOB_RESOURCE_NAME}:run" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data @- <<EOF
{}
EOF

      

반환된 응답은 일괄 작업의 메타데이터와 작업 상태에 대한 정보가 포함된 장기 실행 Operation 객체입니다.

완료될 때까지 일괄 작업의 상태를 폴링합니다.

Operation.done 필드가 true가 될 때까지 google.longrunning.Operations 서비스(BatchJobService와 별개)에서 Operations.GetOperation 메서드를 사용하여 일괄 작업 상태를 폴링합니다. Google Ads API에서 Operations.GetOperation는 google.longrunning.Operations에서 지원되는 유일한 메서드입니다(WaitOperation, ListOperations, CancelOperation, DeleteOperation는 UNIMPLEMENTED를 반환함).

  • 클라이언트 라이브러리: RunBatchJob에서 반환된 장기 실행 작업 래퍼에서 폴링 또는 대기 도우미를 호출하거나(또는 REST 기반 Perl 클라이언트 라이브러리에서 작업 이름을 OperationService::poll_until_done에 전달) 작업이 완료될 때까지(또는 구성된 폴링 제한 시간이 만료될 때까지, Perl에서는 결과를 나열하기 전에 반환된 해시에서 done가 true인지 확인) Operations.GetOperation를 폴링합니다. Java에서는 OperationFuture가 완료될 때까지 BatchJobServiceClient를 열어둡니다.
  • REST: Operation.done 필드가 true가 될 때까지 지수 백오프를 사용하여 HTTP GET 요청을 https://googleads.googleapis.com/v26/OPERATION_NAME(여기서 OPERATION_NAME는 Operation.name 리소스 이름이며 customers/CUSTOMER_ID/operations/OPERATION_ID 형식)에 전송합니다.

자바

private void pollBatchJob(OperationFuture operationResponse) {
  try {
    operationResponse.get(MAX_TOTAL_POLL_INTERVAL_SECONDS, TimeUnit.SECONDS);
  } catch (InterruptedException | ExecutionException | TimeoutException e) {
    System.err.printf("Failed polling the mutate job. Exception: %s%n", e);
    System.exit(1);
  }
}
      

C#

private static void PollBatchJob(Operation<Empty, BatchJobMetadata> operationResponse)
{
    PollSettings pollSettings = new PollSettings(
        Expiration.FromTimeout(TimeSpan.FromSeconds(MAX_TOTAL_POLL_INTERVAL_SECONDS)),
        TimeSpan.FromSeconds(1));
    operationResponse.PollUntilCompleted(pollSettings);
}
      

PHP

private static function pollBatchJob(OperationResponse $operationResponse): void
{
    $operationResponse->pollUntilComplete(
        [
        'initialPollDelayMillis' => self::POLL_FREQUENCY_SECONDS * 1000,
        'totalPollTimeoutMillis' => self::MAX_TOTAL_POLL_INTERVAL_SECONDS * 1000
        ]
    );
}
      

Python

def poll_batch_job(
    operations_response: Operation, event: asyncio.Event
) -> None:
    """Polls the server until the batch job execution finishes.

    Sets the initial poll delay time and the total time to wait before time-out.

    Args:
        operations_response: a google.api_core.operation.Operation instance.
        event: an instance of asyncio.Event to invoke once the operations have
            completed, alerting the awaiting calling code that it can proceed.
    """
    loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()

    def done_callback(future: Coroutine[Any, Any, Any]) -> None:
        # The operations_response object will call callbacks from a daemon
        # thread so we must use a threadsafe method of setting the event here
        # otherwise it will not trigger the awaiting code.
        loop.call_soon_threadsafe(event.set)

    # operations_response represents a Long-Running Operation or LRO. The class
    # provides an interface for polling the API to check when the operation is
    # complete. Below we use the asynchronous interface, but there's also a
    # synchronous interface that uses the Operation.result method.
    # See: https://googleapis.dev/python/google-api-core/latest/operation.html
    operations_response.add_done_callback(done_callback)  # type: ignore
      

Ruby

def poll_batch_job(operation_response)
  operation_response.wait_until_done!
end
      

Perl

sub poll_batch_job {
  my ($operation_service, $batch_job_lro) = @_;

  $operation_service->poll_until_done({
    name                 => $batch_job_lro->{name},
    pollFrequencySeconds => POLL_FREQUENCY_SECONDS,
    pollTimeoutSeconds   => POLL_TIMEOUT_SECONDS
  });
}
      

curl

# Gets the status of a batch job.
#
# Variables:
#   API_VERSION,
#   CUSTOMER_ID,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.
#   BATCH_JOB_OPERATION_NAME:
#     The operation name of the running batch job as returned by the previous
#     step.

curl -f --request GET \
"https://googleads.googleapis.com/v${API_VERSION}/${BATCH_JOB_OPERATION_NAME}" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \

      

또는 GoogleAdsService.Search 또는 GoogleAdsService.SearchStream 메서드를 사용하여 batch_job 리소스를 쿼리하고 batch_job.status 및 특정 BatchJobMetadata 하위 필드(예: batch_job.metadata.estimated_completion_ratio 및 batch_job.metadata.executed_operation_count)를 선택합니다(batch_job.status가 DONE일 때까지). 각 Operations.GetOperation 또는 페이지로 나뉘지 않은 GAQL 요청은 일일 API 할당량에 대해 하나의 작업으로 계산됩니다. 여러 개의 동시 일괄 작업을 모니터링할 때 단일 GAQL 쿼리(WHERE batch_job.id IN (...) 또는 WHERE batch_job.status = 'RUNNING')는 각 장기 실행 작업을 개별적으로 폴링하는 대신 하나의 요청으로 모든 작업을 확인합니다.

Operation.done가 true이면 장기 실행 작업은 작업별 오류 없이 빈 응답을 반환합니다. ListBatchJobResults를 호출하여 개별 작업 결과를 검사합니다.

기존 장기 실행 작업 가져오기

애플리케이션이 별도의 프로세스에서 일괄 작업을 폴링하거나 다시 시작 후 폴링을 재개해야 하는 경우 GoogleAdsService.Search 또는 GoogleAdsService.SearchStream를 사용하여 장기 실행 작업 이름을 검색할 수 있습니다.

  1. batch_job 리소스를 쿼리하여 long_running_operation 필드를 읽습니다.

    SELECT
      batch_job.id,
      batch_job.status,
      batch_job.long_running_operation
    FROM batch_job
    WHERE batch_job.id = BATCH_JOB_ID
    

    BATCH_JOB_ID를 일괄 작업의 숫자 ID로 바꿉니다.

  2. batch_job.status가 RUNNING 또는 DONE인지 확인하고(long_running_operation는 작업이 PENDING인 동안 설정되지 않음. RunBatchJob가 호출될 때까지 장기 실행 작업이 존재하지 않기 때문) 반환된 BatchJob 객체에서 long_running_operation 문자열을 읽습니다.

  3. 작업 이름 문자열을 사용하여 작업을 폴링하거나 검사합니다.

    • 클라이언트 라이브러리: 독립형 OperationsClient를 인스턴스화하는 대신 Google Ads 인증 및 login-customer-id 헤더가 자동으로 구성되도록 BatchJobService 클라이언트(Java 및 PHP의 getOperationsClient(), C#의 RunBatchJobOperationsClient, Python의 transport.operations_client, Ruby의 operations_client, Perl의 $api_client->OperationService())에서 작업 클라이언트를 가져옵니다. 단일 상태 확인을 위해 Operations.GetOperation(또는 Perl의 OperationService::get)를 호출하거나 작업 이름을 사용하여 장기 실행 작업 래퍼를 재개하고 완료될 때까지 폴링합니다(Java의 runBatchJobOperationCallable().resumeFutureCall, C#의 PollOnceRunBatchJob, PHP의 resumeOperation, Python의 get_operation에서 반환된 Operation의 google.api_core.operation.from_gapic, Ruby의 get_operation에서 반환된 Gapic::Operation의 wait_until_done!, Perl의 OperationService::poll_until_done의 name).
    • REST: HTTP GET 요청을 https://googleads.googleapis.com/v26/OPERATION_NAME에 전송합니다.

    OPERATION_NAME는 BatchJob가 생성된 API 메이저 버전을 인코딩하므로, 해당 버전이 종료된 경우 Operations.GetOperation(활성 v26 REST 엔드포인트를 통한 경우에도)는 RequestError.UNSUPPORTED_VERSION 오류와 함께 실패합니다. 대신 GoogleAdsService를 사용하여 batch_job.status를 직접 쿼리합니다.

작업 메타데이터 이해

장기 실행 작업을 폴링하거나 batch_job 리소스를 쿼리하면 BatchJobMetadata에서 일괄 작업 진행 상황에 대한 세부정보를 제공합니다.

이러한 필드, 특히 estimated_completion_ratio 및 작업 수를 사용하면 작업 진행 상황을 측정하고, 남은 시간을 추정하고, 폴링 빈도를 조정할 수 있습니다. 예를 들어 estimated_completion_ratio가 낮으면 폴링 빈도를 줄이고 1.0에 가까워지면 폴링 빈도를 늘릴 수 있습니다.

모든 일괄 작업 결과 나열

일괄 작업이 완료되면 ListBatchJobResults를 호출하여 작업의 각 작업에 대한 상태 및 응답을 검색합니다.

자바

private void fetchAndPrintResults(
    BatchJobServiceClient batchJobServiceClient, String batchJobResourceName) {
  System.out.printf(
      "Mutate job with resource name '%s' has finished. Now, printing its results...%n",
      batchJobResourceName);
  // Gets all the results from running mutate job and prints their information.
  ListBatchJobResultsPagedResponse batchJobResults =
      batchJobServiceClient.listBatchJobResults(
          ListBatchJobResultsRequest.newBuilder()
              .setResourceName(batchJobResourceName)
              .setPageSize(PAGE_SIZE)
              .build());
  for (BatchJobResult batchJobResult : batchJobResults.iterateAll()) {
    System.out.printf(
        "Mutate job #%d has a status '%s' and response of type '%s'.%n",
        batchJobResult.getOperationIndex(),
        batchJobResult.getStatus().getMessage().isEmpty()
            ? "N/A"
            : batchJobResult.getStatus().getMessage(),
        batchJobResult
                .getMutateOperationResponse()
                .getResponseCase()
                .equals(ResponseCase.RESPONSE_NOT_SET)
            ? "N/A"
            : batchJobResult.getMutateOperationResponse().getResponseCase());
  }
}
      

C#

private static void FetchAndPrintResults(BatchJobServiceClient batchJobService,
    string batchJobResourceName)
{
    Console.WriteLine($"batch job with resource name '{batchJobResourceName}' has " +
        $"finished. Now, printing its results...");

    ListBatchJobResultsRequest request = new ListBatchJobResultsRequest()
    {
        ResourceName = batchJobResourceName,
        PageSize = PAGE_SIZE,
    };
    ListBatchJobResultsResponse resp = new ListBatchJobResultsResponse();
    // Gets all the results from running batch job and prints their information.
    foreach (BatchJobResult batchJobResult in
        batchJobService.ListBatchJobResults(request))
    {
        if (!batchJobResult.IsFailed)
        {
            Console.WriteLine($"batch job result #{batchJobResult.OperationIndex} is " +
                $"successful and response is of type " +
                $"'{batchJobResult.MutateOperationResponse.ResponseCase}'.");
        }
        else
        {
            Console.WriteLine($"batch job result #{batchJobResult.OperationIndex} " +
                $"failed with error message {batchJobResult.Status.Message}.");

            foreach (GoogleAdsError error in batchJobResult.Failure.Errors)
            {
                Console.WriteLine($"Error found: {error}.");
            }
        }
    }
}
      

PHP

    private static function fetchAndPrintResults(
        BatchJobServiceClient $batchJobServiceClient,
        string $batchJobResourceName
    ): void {
        printf(
            "Batch job with resource name '%s' has finished. Now, printing its results...%s",
            $batchJobResourceName,
            PHP_EOL
        );
        // Gets all the results from running batch job and print their information.
        $batchJobResults = $batchJobServiceClient->listBatchJobResults(
            ListBatchJobResultsRequest::build($batchJobResourceName)->setPageSize(self::PAGE_SIZE)
        );
        foreach ($batchJobResults->iterateAllElements() as $batchJobResult) {
            /**
 * @var BatchJobResult $batchJobResult
*/
            printf(
                "Batch job #%d has a status '%s' and response of type '%s'.%s",
                $batchJobResult->getOperationIndex(),
                $batchJobResult->getStatus()
                    ? $batchJobResult->getStatus()->getMessage() : 'N/A',
                $batchJobResult->getMutateOperationResponse()
                    ? $batchJobResult->getMutateOperationResponse()->getResponse()
                    : 'N/A',
                PHP_EOL
            );
        }
    }
      

Python

def fetch_and_print_results(
    client: GoogleAdsClient,
    batch_job_service: BatchJobServiceClient,
    resource_name: str,
) -> None:
    """Prints all the results from running the batch job.

    Args:
        client: an initialized GoogleAdsClient instance.
        batch_job_service: an instance of the BatchJobService message class.
        resource_name: a str of a resource name for a batch job.
    """
    print(
        f'Batch job with resource name "{resource_name}" has finished. '
        "Now, printing its results..."
    )

    list_results_request: ListBatchJobResultsRequest = client.get_type(
        "ListBatchJobResultsRequest"
    )
    list_results_request.resource_name = resource_name
    list_results_request.page_size = 1000
    # Gets all the results from running batch job and prints their information.
    batch_job_results: ListBatchJobResultsResponse = (
        batch_job_service.list_batch_job_results(request=list_results_request)
    )

    for batch_job_result in batch_job_results:
        status: str = batch_job_result.status.message
        status = status if status else "N/A"
        result: Any = batch_job_result.mutate_operation_response
        result = result or "N/A"
        print(
            f"Batch job #{batch_job_result.operation_index} "
            f'has a status "{status}" and response type "{result}"'
        )
      

Ruby

def fetch_and_print_results(batch_job_service, batch_job_resource_name)
  puts "Batch job with resource name '#{batch_job_resource_name}' has " \
    "finished. Now, printing its results..." \

  # Gets all the results from running batch job and print their information.
  batch_job_results = batch_job_service.list_batch_job_results(
    resource_name: batch_job_resource_name,
    page_size: PAGE_SIZE,
  )
  batch_job_results.each do |result|
    puts "Batch job ##{result.operation_index} has a status " \
      "#{result.status ? result.status.message : 'N/A'} and response of type " \
      "#{result.mutate_operation_response ? result.mutate_operation_response.response : 'N/A'}"
  end
end
      

Perl

sub fetch_and_print_results {
  my ($batch_job_service, $batch_job_resource_name) = @_;

  printf "Batch job with resource name '%s' has finished. " .
    "Now, printing its results...\n", $batch_job_resource_name;

  # Get all the results from running batch job and print their information.
  my $list_batch_job_results_response = $batch_job_service->list_results({
    resourceName => $batch_job_resource_name,
    pageSize     => PAGE_SIZE
  });

  foreach my $batch_job_result (@{$list_batch_job_results_response->{results}})
  {
    printf
      "Batch job #%d has a status '%s' and response of type '%s'.\n",
      $batch_job_result->{operationIndex},
      $batch_job_result->{status} ? $batch_job_result->{status}{message}
      : "N/A",
      $batch_job_result->{mutateOperationResponse}
      ? [keys %{$batch_job_result->{mutateOperationResponse}}]->[0]
      : "N/A";
  }
}
      

curl

# Gets the results of a batch job.
#
# Variables:
#   API_VERSION,
#   CUSTOMER_ID,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.
#   BATCH_JOB_RESOURCE_NAME:
#     The operation name of the running batch job as returned by the previous
#     step.
curl -f --request GET \
"https://googleads.googleapis.com/v${API_VERSION}/${BATCH_JOB_RESOURCE_NAME}:listResults?pageSize=1000" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}"

      

ListBatchJobResultsRequest에서 page_size 필드는 생략되거나 0로 설정된 경우 기본적으로 최댓값인 1000로 설정됩니다. page_size를 1000보다 크거나 0보다 작은 값으로 설정하면 BatchJobError.INVALID_PAGE_SIZE 오류가 반환됩니다.

각 BatchJobResult는 일괄 작업에서 업로드된 MutateOperation의 0부터 시작하는 색인인 operation_index를 사용하여 해당 작업을 식별합니다.

일괄 작업 취소 또는 삭제

일괄 작업을 중지하거나 삭제하는 방법은 RunBatchJob가 호출되었는지 여부에 따라 다릅니다.

오류 처리

BatchJobService는 부분 실패가 사용 설정된 상태에서 표준 작업을 실행하고(원자적 하위 배치 내를 제외하고 동일한 작업의 다른 작업이 실패하더라도 성공적인 작업이 커밋됨) 일시적인 오류로 인해 실패한 작업을 자동으로 다시 시도합니다. 하지만 모든 실패 시나리오를 피할 수는 없습니다. 유효성 검사 오류로 인해 실패한 작업은 수정하여 새 일괄 작업으로 다시 제출할 수 있습니다. 마찬가지로 일괄 작업이 모든 작업을 완료하기 전에 취소되거나 중단되면 실행되지 않은 작업(operation_index >= executed_operation_count)을 실행된 프리픽스의 실패한 작업과 함께 새 일괄 작업으로 다시 제출할 수 있습니다.