使用批次處理的步驟如下:
建立新的批次工作
如要建立 BatchJob 資源,請呼叫 MutateBatchJob。建構 BatchJob 物件時,您可以選擇將 metadata.execution_limit_seconds 設為正整數,以秒為單位設定工作自動取消前可執行的約略上限時間 (請參閱「其他使用指南」)。
Java
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
小茹
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
在批次工作中新增變動操作
呼叫 AddBatchJobOperations,將一或多個 MutateOperation 物件新增至上一步建立的批次工作。回應會包含下列內容:
total_operations:目前 為止為這項工作新增的作業總數。next_sequence_token:再次呼叫這個方法來新增更多作業時,要在sequence_token欄位中傳遞的序列權杖。
批次工作的初始 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 指定資源名稱。
Java
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)
小茹
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 中用戶端程式庫建構作業函式的內容:
Java
buildAllOperations()
C#
BuildAllOperations()
PHP
buildAllOperations()
Python
build_all_operations()
小茹
build_all_operations()
Perl
build_all_operations
執行批次工作
新增所有作業後,您可以對上傳的作業呼叫 RunBatchJob,要求 Google Ads API 執行批次工作。在工作開始執行後呼叫 RunBatchJob,會傳回 BatchJobError.CANNOT_MODIFY_JOB_AFTER_JOB_STARTS_RUNNING 錯誤。
Java
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
小茹
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 物件,其中包含批次工作的元資料和工作狀態資訊。
輪詢批次工作的狀態,直到完成為止
使用 google.longrunning.Operations 服務 (與 BatchJobService 分開) 的 Operations.GetOperation 方法輪詢批次工作狀態,直到 Operation.done 欄位為 true 為止。在 Google Ads API 中,google.longrunning.Operations 僅支援 Operations.GetOperation 方法 (WaitOperation、ListOperations、CancelOperation 和 DeleteOperation 會傳回 UNIMPLEMENTED):
- 用戶端程式庫:在
RunBatchJob傳回的長時間執行作業包裝函式上,呼叫輪詢或等待輔助程式 (或在以 REST 為基礎的 Perl 用戶端程式庫中,將作業名稱傳遞至OperationService::poll_until_done),這會輪詢Operations.GetOperation,直到作業完成 (或設定的輪詢逾時時間到期;在 Perl 中,請先確認傳回雜湊上的done為true,再列出結果)。在 Java 中,請保持BatchJobServiceClient開啟,直到OperationFuture完成。 - REST:向
https://googleads.googleapis.com/v26/OPERATION_NAME傳送 HTTPGET要求 (其中OPERATION_NAME是Operation.name資源名稱,格式為customers/CUSTOMER_ID/operations/OPERATION_ID),並使用指數輪詢,直到Operation.done欄位為true。
Java
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
小茹
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 擷取長時間執行的作業名稱:
查詢
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。確認
batch_job.status為RUNNING或DONE(工作為PENDING時,long_running_operation未設定,因為在呼叫RunBatchJob之前,沒有長時間執行的作業),並從傳回的BatchJob物件讀取long_running_operation字串。使用該作業名稱字串輪詢或檢查作業:
- 用戶端程式庫:從
BatchJobService用戶端 (Java 和 PHP 中的getOperationsClient()、C# 中的RunBatchJobOperationsClient、Python 中的transport.operations_client、Ruby 中的operations_client或 Perl 中的$api_client->OperationService()) 取得作業用戶端,以便自動設定 Google Ads 驗證和login-customer-id標頭,而不是例項化獨立OperationsClient。呼叫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(即使透過有效的v26REST 端點) 會失敗,並顯示RequestError.UNSUPPORTED_VERSION錯誤。請改用GoogleAdsService直接查詢batch_job.status。- 用戶端程式庫:從
瞭解作業中繼資料
輪詢長時間執行的作業或查詢 batch_job 資源時,BatchJobMetadata 會提供批次工作進度的詳細資料:
creation_date_time:建立批次工作的時間戳記。start_date_time:批次工作開始執行的時間戳記 (使用GoogleAdsService查詢batch_job.metadata.start_date_time時填入;在RunBatchJob和Operations.GetOperation中,Operation.metadata會省略)。completion_date_time:批次工作完成時的時間戳記 (僅在工作完成時顯示)。estimated_completion_ratio:工作完成比例的預估值 (從 0.0 到 1.0)。operation_count:批次工作中的作業總數。executed_operation_count:目前已執行的作業數量。execution_limit_seconds:批次工作在取消前可執行的約略上限時間 (以秒為單位)。如果在建立工作時設定了正數限制,則使用GoogleAdsService查詢batch_job.metadata.execution_limit_seconds時會填入此值;在RunBatchJob和Operations.GetOperation中,Operation.metadata會省略此值。
這些欄位 (尤其是 estimated_completion_ratio 和作業計數) 可協助您評估工作進度、預估剩餘時間,以及調整輪詢頻率。舉例來說,當 estimated_completion_ratio 較低時,您可以降低輪詢頻率,並在接近 1.0 時提高頻率。
列出所有批次工作結果
批次工作完成後,請呼叫 ListBatchJobResults,擷取工作中每項作業的狀態和回應:
Java
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}"' )
小茹
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 都會使用 operation_index (批次工作中上傳的 MutateOperation 的 0 索引) 來識別對應的作業。
- 作業成功:系統會填入
mutate_operation_response(其response包含已變動資源的resource_name,如果response_content_type設為MUTABLE_RESOURCE,則還會包含所有可變動欄位),且status未設定。 - 失敗 (或未執行) 的作業:未設定
mutate_operation_response,且status包含作業的錯誤詳細資料。
取消或移除批次工作
停止或捨棄批次工作的方式,取決於是否已呼叫 RunBatchJob:
- 呼叫
RunBatchJob之前:如果工作的status為PENDING,您可以使用BatchJobOperation.remove呼叫MutateBatchJob來捨棄批次工作。在工作開始執行後呼叫remove,會傳回BatchJobError.CAN_ONLY_REMOVE_PENDING_JOB錯誤。 - 呼叫
RunBatchJob後:您無法手動取消執行中的批次工作 (Google Ads API 未實作Operations.CancelOperation,且會傳回UNIMPLEMENTED)。如要限制執行時間,讓工作在執行時間過長時自動取消,請在MutateBatchJob中建立工作時,將metadata.execution_limit_seconds設為正整數 (約略上限)。由於批次工作中的標準作業會在啟用部分失敗的情況下執行 (完整子批次中的作業會一併復原),因此自動取消不會復原已完成的作業。取消 (或中止) 工作的status轉換為DONE後,呼叫ListBatchJobResults會傳回已執行前置字元 (operation_index<executed_operation_count) 的BatchJobResult項目及其個別執行結果,接著是所有剩餘未執行作業 (operation_index,從executed_operation_count到operation_count- 1) 的BatchJobResult項目,其中mutate_operation_response未設定,且status設為ABORTED,並在因execution_limit_seconds取消時顯示InternalError.INTERNAL_ERROR(或在工作因嚴重執行錯誤而中止時,設為工作層級錯誤狀態)。
錯誤處理
BatchJobService 會在啟用部分失敗的情況下執行標準作業 (即使同一工作中的其他作業失敗,成功的作業也會提交,但不可分割式子批次中的作業除外),並自動重試因暫時性錯誤而失敗的作業。不過,並非所有故障情況都能避免。您可以修正因驗證錯誤而失敗的操作,並在新的批次工作中重新提交。同樣地,如果批次工作在完成所有作業前取消或中止,您可以將未執行的作業 (operation_index >= executed_operation_count) 以及已執行前置字串中任何失敗的作業,一併重新提交至新的批次工作。