Operazioni a lunga esecuzione (LRO)

Diverse chiamate all'API Google Ads restituiscono operazioni a lunga esecuzione (LRO). Queste tengono traccia dello stato di un job che viene eseguito per un periodo di tempo prolungato senza richiedere un singolo RPC di blocco.

Classe OperationFuture

Interagisci con le LRO nella libreria client Java utilizzando la OperationFuture classe. Poiché OperationFuture si basa sul client di servizio sottostante per eseguire il polling dell'API per gli aggiornamenti di stato, assicurati che il client di servizio rimanga aperto e attivo fino al completamento dell'operazione.

Non consigliato:

private void executeOperation(String jobName) throws Exception {
  OperationFuture<Empty, OfflineUserDataJobMetadata> future =
      startLongRunningOperation(jobName);
  // FAILS: The service client was already closed when
  // startLongRunningOperation() exited its try-with-resources block, so
  // future.get() fails when polling.
  future.get();
}

private OperationFuture<Empty, OfflineUserDataJobMetadata>
    startLongRunningOperation(String jobToStart) {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient
          .getLatestVersion()
          .createOfflineUserDataJobServiceClient()) {
    // Issues an asynchronous request to run the offline user data job.
    return offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(
        jobToStart);
  }
}

Consigliato:

private void executeOperation(String jobName) throws Exception {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient
          .getLatestVersion()
          .createOfflineUserDataJobServiceClient()) {
    OperationFuture<Empty, OfflineUserDataJobMetadata> future =
        startLongRunningOperation(offlineUserDataJobServiceClient, jobName);
    // Waits for the operation to complete (with a timeout) while the client is
    // still open.
    future.get(5, TimeUnit.MINUTES);
  }
}

private OperationFuture<Empty, OfflineUserDataJobMetadata>
    startLongRunningOperation(
        OfflineUserDataJobServiceClient offlineUserDataJobServiceClient,
        String jobToStart) {
  return offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
}

Nota come OperationFuture viene utilizzato solo mentre OfflineUserDataJobServiceClient rimane aperto all'interno del blocco try-with-resources.