タスクのステータスをポーリングする

アップロードされた構造化データファイルによって、リソースが即座に作成または更新されることはありません。ディスプレイ&ビデオ 360 で SDF を処理し、更新を反映するまでに数秒から数時間かかることがあります。リソースが重複していなければ、複数のファイルを同時にアップロードできます。

タスクが完了したかどうかを確認するには、sdfuploadtasks.operations.get を使用してオペレーションを定期的に取得し、done フィールドが True で、タスクが完了しているかどうかを確認します。このプロセスを「ポーリング」と呼びます。

タスクが完了すると、response フィールドまたは error フィールドのいずれかが設定されます。error フィールドに入力されている場合、タスクは失敗しており、失敗に関する詳細は結果の Status オブジェクトで確認できます。response フィールドに値が入力されている場合、SdfUploadTask がフィールドに割り当てられます。これは、ディスプレイ&ビデオ 360 でアップロードされた SDF が正常に処理されたことを意味します。SdfUploadTask.resourceName フィールドで指定された場所から結果ファイルをダウンロードします。

長時間実行されるレポートをチェックするポーリング実装の効率が悪いと、API リクエストの割り当てを大量に消費します。再試行を制限して割り当てを節約するには、指数バックオフを使用します。

指数バックオフを使用して SDF アップロード オペレーションをポーリングする方法は次のとおりです。

# Import the necessary libraries
import random
import time

# Provide the name of the sdfuploadtask operation.
operation_name = operation-name

# Set the following values that control retry behavior while the operation
# is running.
# Minimum amount of time between polling requests. Defaults to 5 seconds.
min_retry_interval = 5
# Maximum amount of time between polling requests. Defaults to 5 minutes.
max_retry_interval = 5 * 60
# Maximum amount of time to spend polling. Defaults to 5 hours.
max_retry_elapsed_time = 5 * 60 * 60

# Configure the sdfuploadtasks.operations.get request.
get_request = service.sdfuploadtasks().operations().get(operation_name)

sleep = 0

start_time = time.time()
while True:
  # Get current status of the report.
  operation = get_request.execute()

  if "done" in operation:
    if "error" in operation:
      print(
        f'The operation finished in error with code '
        f'{operation["error"]["code"]}: {operation["error"]["message"]}')
    else:
      print(
        f'The operation completed successfully. The result files can be '
        f'downloaded at {operation["response"]["resourceName"]}.')
    break
  elif time.time() - start_time > max_retry_elapsed_time:
    print("Polling deadline exceeded.")
    break

  sleep = next_sleep_interval(sleep)
  print(
    f'Operation {operation_name} is still running, sleeping for '
    f'{sleep} seconds.')
  time.sleep(sleep)

def next_sleep_interval(previous_sleep_interval):
  """Calculates the next sleep interval based on the previous."""
  min_interval = previous_sleep_interval or min_retry_interval
  max_interval = previous_sleep_interval * 3 or min_retry_interval
  return min(max_retry_interval, random.randint(min_interval, max_interval))