使用 Cloud 用戶端程式庫執行工作流程

本快速入門導覽課程說明如何使用 Cloud 用戶端程式庫執行工作流程,並查看執行結果。

如要進一步瞭解如何安裝 Cloud 用戶端程式庫及設定開發環境,請參閱「工作流程用戶端程式庫總覽」。

您可以在終端機或 Cloud Shell 中使用 Google Cloud CLI 完成下列步驟。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 Google Cloud 環境中開發應用程式」。

  1. 安裝 Google Cloud CLI。

  2. 設定 gcloud CLI,使用您的聯合身分。

    詳情請參閱「使用聯合身分登入 gcloud CLI」。

  3. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  4. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您在專案中獲派角色,即可選取該專案。
    • 建立專案:如要建立專案,您需要專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  5. 如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。

  6. 確認專案已啟用計費功能 Google Cloud

  7. 啟用 Workflows API:

    啟用 API 時所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色

    gcloud services enable workflows.googleapis.com
  8. 設定驗證方法:

    1. 確認您具備「建立服務帳戶」身分與存取權管理角色 (roles/iam.serviceAccountCreator) 和「專案 IAM 管理員」角色 (roles/resourcemanager.projectIamAdmin)。瞭解如何授予角色
    2. 建立服務帳戶:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME 換成服務帳戶的名稱。

    3. roles/logging.logWriter 身分與存取權管理角色授予服務帳戶:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID." --role=roles/logging.logWriter

      請替換下列項目:

      • SERVICE_ACCOUNT_NAME:服務帳戶名稱
      • PROJECT_ID:您建立服務帳戶的專案 ID
  9. 如要進一步瞭解服務帳戶角色和權限,請參閱授予工作流程存取Google Cloud 資源的權限

  10. 視需要下載並安裝 Git 原始碼管理工具。

必要的角色

如要取得完成本快速入門導覽課程所需的權限,請要求管理員在專案中授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

部署範例工作流程

定義工作流程後,請部署工作流程,以便執行。部署步驟也會驗證來源檔案是否可執行。

下列工作流程會將要求傳送至公用 API,然後傳回 API 的回應。

  1. 建立名為 myFirstWorkflow.yaml 的文字檔,並在當中加入下列內容:

    # This workflow accepts an optional "searchTerm" argument for the Wikipedia API.
    # If no input arguments are provided or "searchTerm" is absent,
    # it will fetch the day of the week in Amsterdam and use it as the search term.
    
    main:
        params: [input]
        steps:
        - validateSearchTermAndRedirectToReadWikipedia:
            switch:
                - condition: '${map.get(input, "searchTerm") != null}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
        - getCurrentTime:
            call: http.get
            args:
                url: https://timeapi.io/api/Time/current/zone?timeZone=Europe/Amsterdam
            result: currentTime
        - setFromCallResult:
            assign:
                - searchTerm: '${currentTime.body.dayOfWeek}'
        - readWikipedia:
            call: http.get
            args:
                url: 'https://en.wikipedia.org/w/api.php'
                query:
                    action: opensearch
                    search: '${searchTerm}'
            result: wikiResult
        - returnOutput:
                return: '${wikiResult.body[1]}'
  2. 建立工作流程後,您可以部署工作流程,但請勿執行工作流程:

    gcloud workflows deploy myFirstWorkflow \
        --source=myFirstWorkflow.yaml \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID. \
        --location=CLOUD_REGION

    CLOUD_REGION 替換為工作流程的支援位置。程式碼範例中使用的預設區域為 us-central1

取得程式碼範例

您可以從 GitHub 複製程式碼範例。

  1. 將應用程式存放區範例複製到本機電腦中:

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    您也可以下載 zip 格式的範例檔案,然後將檔案解壓縮。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    您也可以下載 zip 格式的範例檔案,然後將檔案解壓縮。

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    您也可以下載 zip 格式的範例檔案,然後將檔案解壓縮。

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    您也可以下載 zip 格式的範例檔案,然後將檔案解壓縮。

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    您也可以下載 zip 格式的範例檔案,然後將檔案解壓縮。

  2. 變更為包含 Workflows 範例程式碼的目錄:

    C#

    cd dotnet-docs-samples/workflows/api/Workflow.Samples/

    Go

    cd golang-samples/workflows/executions/

    Java

    cd java-docs-samples/workflows/cloud-client/

    Node.js

    cd nodejs-docs-samples/workflows/quickstart/

    Python

    cd python-docs-samples/workflows/cloud-client/

  3. 查看程式碼範例,每個範例應用程式都會執行下列操作:

    1. 設定 Workflows 適用的 Cloud 用戶端程式庫。
    2. 執行工作流程。
    3. 輪詢工作流程的執行作業 (使用指數輪詢),直到執行作業終止為止。
    4. 列印執行結果。

    C#

    
    using Google.Cloud.Workflows.Common.V1;
    using Google.Cloud.Workflows.Executions.V1;
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class ExecuteWorkflowSample
    {
        /// <summary>
        /// Execute a workflow and return the execution operation.
        /// </summary>
        /// <param name="projectID">Your Google Cloud Project ID.</param>
        /// <param name="locationID">The region where your workflow is located.</param>
        /// <param name="workflowID">Your Workflow ID.</param>
        /// <returns>
        /// An Execute object representing the completed workflow execution.
        /// </returns>
        public async Task<Execution> ExecuteWorkflow(
            string projectId = "YOUR-PROJECT-ID",
            string locationID = "YOUR-LOCATION-ID",
            string workflowID = "YOUR-WORKFLOW-ID")
        {
            // Initialize the client.
            ExecutionsClient client = await ExecutionsClient.CreateAsync();
    
            // Build the parent location path.
            WorkflowName parent = new WorkflowName(projectId, locationID, workflowID);
    
            // Create an execution request.
            CreateExecutionRequest createExecutionRequest = new CreateExecutionRequest
            {
                ParentAsWorkflowName = parent,
            };
    
            // Execute the operation.
            Execution execution = await client.CreateExecutionAsync(createExecutionRequest);
            Console.WriteLine("- Execution started...");
    
            TimeSpan backoffDelay = TimeSpan.FromSeconds(1);
            TimeSpan maxBackoffDelay = TimeSpan.FromSeconds(16);
    
            // Keep polling the state until the execution finishes, using exponential backoff.
            while (execution.State == Execution.Types.State.Active)
            {
                await Task.Delay(backoffDelay);
    
                // Implement exponential backoff by doubling the delay, but limiting it to a practical duration.
                backoffDelay = (backoffDelay < maxBackoffDelay) ? backoffDelay * 2 : maxBackoffDelay;
    
                execution = await client.GetExecutionAsync(execution.Name);
            }
    
            // Print results.
            Console.WriteLine($"Execution finished with state: {execution.State}");
            Console.WriteLine($"Execution results: {execution.Result}");
    
            // Return the fetched execution.
            return execution;
        }
    }

    Go

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	workflowexecutions "google.golang.org/api/workflowexecutions/v1"
    )
    
    // Execute a workflow and print the execution results.
    //
    // For more information about Workflows see:
    // https://cloud.google.com/workflows/docs/overview
    func executeWorkflow(w io.Writer, projectID, workflowID, locationID string) error {
    	// TODO(developer): Uncomment and update the following lines:
    	// projectID := "YOUR_PROJECT_ID"
    	// workflowID := "YOUR_WORKFLOW_ID"
    	// locationID := "YOUR_LOCATION_ID"
    
    	ctx := context.Background()
    
    	// Construct the location path.
    	parent := fmt.Sprintf("projects/%s/locations/%s/workflows/%s", projectID, locationID, workflowID)
    
    	// Create execution client.
    	client, err := workflowexecutions.NewService(ctx)
    	if err != nil {
    		return fmt.Errorf("workflowexecutions.NewService error: %w", err)
    	}
    
    	// Get execution service.
    	service := client.Projects.Locations.Workflows.Executions
    
    	// Build and run the new workflow execution.
    	res, err := service.Create(parent, &workflowexecutions.Execution{}).Do()
    	if err != nil {
    		return fmt.Errorf("service.Create.Do error: %w", err)
    	}
    	fmt.Fprintln(w, "- Execution started...")
    
    	// Set initial value for backoff delay in one second.
    	backoffDelay := time.Second
    
    	for res.State == "ACTIVE" {
    		time.Sleep(backoffDelay)
    
    		// Request the updated state for the execution.
    		getReq := service.Get(res.Name)
    		res, err = getReq.Do()
    		if err != nil {
    			return fmt.Errorf("getReq error: %w", err)
    		}
    
    		// Double the delay to provide exponential backoff (capped at 16 seconds).
    		if backoffDelay < time.Second*16 {
    			backoffDelay *= 2
    		}
    	}
    
    	fmt.Fprintf(w, "Execution finished with state: %s\n", res.State)
    	fmt.Fprintf(w, "Execution results: %s\n", res.Result)
    
    	return nil
    }
    

    Java

    
    import com.google.cloud.workflows.executions.v1.CreateExecutionRequest;
    import com.google.cloud.workflows.executions.v1.Execution;
    import com.google.cloud.workflows.executions.v1.ExecutionsClient;
    import com.google.cloud.workflows.executions.v1.WorkflowName;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    public class ExecuteWithoutArguments {
      public static void main(String[] args)
          throws IOException, InterruptedException, ExecutionException {
        String projectId = "your-project-id";
        String location = "your-location"; // For example: us-central1
        String workflowId = "your-workflow-id";
    
        executeWorkflowWithoutArguments(projectId, location, workflowId);
      }
    
      public static void executeWorkflowWithoutArguments(
          String projectId, String location, String workflowId)
          throws IOException, InterruptedException, ExecutionException {
        try (ExecutionsClient executionsClient = ExecutionsClient.create()) {
          WorkflowName parent = WorkflowName.of(projectId, location, workflowId);
    
          CreateExecutionRequest executionRequest =
              CreateExecutionRequest.newBuilder()
                  .setParent(parent.toString())
                  .setExecution(Execution.newBuilder().build())
                  .build();
    
          Execution executionCreated = executionsClient.createExecution(executionRequest);
    
          System.out.println("Created execution: " + executionCreated.getName());
    
          // Wait for execution to finish using exponential backoff
          long backoffDelay = 1_000;
          Execution execution;
          System.out.println("Poll for result...");
          while (true) {
            execution = executionsClient.getExecution(executionCreated.getName());
    
            // Check if execution finished
            if (execution.getState() != Execution.State.ACTIVE) {
              break;
            }
    
            // Wait using exponential backoff
            System.out.println("- Waiting for results...");
            Thread.sleep(backoffDelay);
            backoffDelay *= 2;
          }
    
          System.out.println("Execution finished with state: " + execution.getState().name());
          System.out.println("Execution results: " + execution.getResult());
        }
      }
    }

    Node.js

    const {ExecutionsClient} = require('@google-cloud/workflows');
    const client = new ExecutionsClient();
    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project';
    // const location = 'us-central1';
    // const workflow = 'myFirstWorkflow';
    // const searchTerm = '';
    
    /**
     * Executes a Workflow and waits for the results with exponential backoff.
     * @param {string} projectId The Google Cloud Project containing the workflow
     * @param {string} location The workflow location
     * @param {string} workflow The workflow name
     * @param {string} searchTerm Optional search term to pass to the Workflow as a runtime argument
     */
    async function executeWorkflow(projectId, location, workflow, searchTerm) {
      /**
       * Sleeps the process N number of milliseconds.
       * @param {Number} ms The number of milliseconds to sleep.
       */
      function sleep(ms) {
        return new Promise(resolve => {
          setTimeout(resolve, ms);
        });
      }
      const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {};
      // Execute workflow
      try {
        const createExecutionRes = await client.createExecution({
          parent: client.workflowPath(projectId, location, workflow),
          execution: {
            // Runtime arguments can be passed as a JSON string
            argument: JSON.stringify(runtimeArgs),
          },
        });
        const executionName = createExecutionRes[0].name;
        console.log(`Created execution: ${executionName}`);
    
        // Wait for execution to finish, then print results.
        let executionFinished = false;
        let backoffDelay = 1000; // Start wait with delay of 1,000 ms
        console.log('Poll every second for result...');
        while (!executionFinished) {
          const [execution] = await client.getExecution({
            name: executionName,
          });
          executionFinished = execution.state !== 'ACTIVE';
    
          // If we haven't seen the result yet, wait a second.
          if (!executionFinished) {
            console.log('- Waiting for results...');
            await sleep(backoffDelay);
            backoffDelay *= 2; // Double the delay to provide exponential backoff.
          } else {
            console.log(`Execution finished with state: ${execution.state}`);
            console.log(execution.result);
            return execution.result;
          }
        }
      } catch (e) {
        console.error(`Error executing workflow: ${e}`);
      }
    }
    
    executeWorkflow(projectId, location, workflowName, searchTerm).catch(err => {
      console.error(err.message);
      process.exitCode = 1;
    });
    

    Python

    import time
    
    from google.cloud import workflows_v1
    from google.cloud.workflows import executions_v1
    
    from google.cloud.workflows.executions_v1.types import executions
    
    # TODO(developer): Update and uncomment the following lines.
    # project_id = "YOUR_PROJECT_ID"
    # location = "YOUR_LOCATION"  # For example: us-central1
    # workflow_id = "YOUR_WORKFLOW_ID"  # For example: myFirstWorkflow
    
    # Initialize API clients.
    execution_client = executions_v1.ExecutionsClient()
    workflows_client = workflows_v1.WorkflowsClient()
    
    # Construct the fully qualified location path.
    parent = workflows_client.workflow_path(project_id, location, workflow_id)
    
    # Execute the workflow.
    response = execution_client.create_execution(request={"parent": parent})
    print(f"Created execution: {response.name}")
    
    # Wait for execution to finish, then print results.
    execution_finished = False
    backoff_delay = 1  # Start wait with delay of 1 second.
    print("Poll for result...")
    
    # Keep polling the state until the execution finishes,
    # using exponential backoff.
    while not execution_finished:
        execution = execution_client.get_execution(
            request={"name": response.name}
        )
        execution_finished = execution.state != executions.Execution.State.ACTIVE
    
        # If we haven't seen the result yet, keep waiting.
        if not execution_finished:
            print("- Waiting for results...")
            time.sleep(backoff_delay)
            # Double the delay to provide exponential backoff.
            backoff_delay *= 2
        else:
            print(f"Execution finished with state: {execution.state.name}")
            print(f"Execution results: {execution.result}")

執行程式碼範例

您可以執行程式碼範例,並執行工作流程。執行工作流程時,系統會執行與該工作流程相關聯的已部署工作流程定義。

  1. 如要執行範例,請先安裝依附元件:

    C#

    dotnet restore

    Go

    go mod download

    Java

    mvn compile

    Node.js

    npm install -D tsx

    Python

    pip3 install -r requirements.txt

  2. 執行指令碼:

    C#

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME dotnet run

    Go

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME go run .

    Java

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME mvn compile exec:java -Dexec.mainClass=com.example.workflows.WorkflowsQuickstart

    Node.js

    npx tsx index.js

    Python

    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME python3 main.py

    更改下列內容:

    • PROJECT_ID:您的 Google Cloud 專案名稱
    • CLOUD_REGION:工作流程的位置 (預設值:us-central1)
    • WORKFLOW_NAME:工作流程名稱 (預設值:myFirstWorkflow)

    輸出結果會與下列內容相似:

    Execution finished with state: SUCCEEDED
    Execution results: ["Thursday","Thursday Night Football","Thursday (band)","Thursday Island","Thursday (album)","Thursday Next","Thursday at the Square","Thursday's Child (David Bowie song)","Thursday Afternoon","Thursday (film)"]
    

在執行要求中傳遞資料

視用戶端程式庫語言而定,您也可以在執行要求中傳遞執行階段引數。例如:

C#


public class ExecuteWorkflowWithArgumentsSample
{
    /// <summary>
    /// Execute a workflow with arguments and return the execution operation.
    /// </summary>
    /// <param name="projectID">Your Google Cloud Project ID.</param>
    /// <param name="locationID">The region where your workflow is located.</param>
    /// <param name="workflowID">Your Workflow ID.</param>
    /// <returns>
    /// An Execute object representing the completed workflow execution.
    /// </returns>
    public async Task<Execution> ExecuteWorkflowWithArguments(
        string projectId = "YOUR-PROJECT-ID",
        string locationID = "YOUR-LOCATION-ID",
        string workflowID = "YOUR-WORKFLOW-ID")
    {
        // Initialize the client.
        ExecutionsClient client = await ExecutionsClient.CreateAsync();

        // Build the parent location path.
        WorkflowName parent = new WorkflowName(projectId, locationID, workflowID);

        // Serialize the argument.
        string argument = JsonSerializer.Serialize(new
        {
            searchTerm = "Cloud"
        });

        // Create an execution request.
        CreateExecutionRequest createExecutionRequest = new CreateExecutionRequest
        {
            ParentAsWorkflowName = parent,
            Execution = new Execution
            {
                Argument = argument,
            }
        };

        // Execute the operation and recieve the execution.
        Execution execution = await client.CreateExecutionAsync(createExecutionRequest);
        Console.WriteLine("- Execution started...");

        TimeSpan backoffDelay = TimeSpan.FromSeconds(1);
        TimeSpan maxBackoffDelay = TimeSpan.FromSeconds(16);

        // Keep polling the state until the execution finishes, using exponential backoff.
        while (execution.State == Execution.Types.State.Active)
        {
            await Task.Delay(backoffDelay);

            // Implement exponential backoff by doubling the delay, but limiting it to a practical duration.
            backoffDelay = (backoffDelay < maxBackoffDelay) ? backoffDelay * 2 : maxBackoffDelay;

            execution = await client.GetExecutionAsync(execution.Name);
        }

        // Print results.
        Console.WriteLine($"Execution finished with state: {execution.State}");
        Console.WriteLine($"Execution results: {execution.Result}");

        // Return the fetched execution.
        return execution;
    }
}

Go

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"time"

	workflowexecutions "google.golang.org/api/workflowexecutions/v1"
)

// Execute a workflow with arguments and print the execution results.
//
// For more information about Workflows see:
// https://cloud.google.com/workflows/docs/overview
func executeWorkflowWithArguments(w io.Writer, projectID, workflowID, locationID string) error {
	// TODO(developer): Uncomment and update the following lines:
	// projectID := "YOUR_PROJECT_ID"
	// workflowID := "YOUR_WORKFLOW_ID"
	// locationID := "YOUR_LOCATION_ID"

	ctx := context.Background()

	// Construct the location path.
	parent := fmt.Sprintf("projects/%s/locations/%s/workflows/%s", projectID, locationID, workflowID)

	// Create execution client.
	client, err := workflowexecutions.NewService(ctx)
	if err != nil {
		return fmt.Errorf("workflowexecutions.NewService error: %w", err)
	}

	// Get execution service.
	service := client.Projects.Locations.Workflows.Executions

	// Create argument.
	argument := struct {
		SearchTerm string `json:"searchTerm"`
	}{
		SearchTerm: "Cloud",
	}

	// Encode argument to JSON.
	argumentEncoded, err := json.Marshal(argument)
	if err != nil {
		return fmt.Errorf("json.Marshal error: %w", err)
	}

	// Build and run the new workflow execution adding the argument.
	res, err := service.Create(parent, &workflowexecutions.Execution{
		Argument: string(argumentEncoded),
	}).Do()
	if err != nil {
		return fmt.Errorf("service.Create.Do error: %w", err)
	}
	fmt.Fprintln(w, "- Execution started...")

	// Set initial value for backoff delay in one second.
	backoffDelay := time.Second

	for res.State == "ACTIVE" {
		time.Sleep(backoffDelay)

		// Request the updated state for the execution.
		getReq := service.Get(res.Name)
		res, err = getReq.Do()
		if err != nil {
			return fmt.Errorf("getReq error: %w", err)
		}

		// Double the delay to provide exponential backoff (capped at 16 seconds).
		if backoffDelay < time.Second*16 {
			backoffDelay *= 2
		}
	}

	fmt.Fprintf(w, "Execution finished with state: %s\n", res.State)
	fmt.Fprintf(w, "Execution arguments: %s", res.Argument)
	fmt.Fprintf(w, "Execution results: %s\n", res.Result)

	return nil
}

Java


public class ExecuteWithArguments {
  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException {
    String projectId = "your-project-id";
    String location = "your-location"; // For example: us-central1
    String workflowId = "your-workflow-id";

    executeWorkflowWithArguments(projectId, location, workflowId);
  }

  public static void executeWorkflowWithArguments(
      String projectId, String location, String workflowId)
      throws IOException, InterruptedException, ExecutionException {
    try (ExecutionsClient executionsClient = ExecutionsClient.create()) {
      WorkflowName parent = WorkflowName.of(projectId, location, workflowId);

      CreateExecutionRequest executionRequest =
          CreateExecutionRequest.newBuilder()
              .setParent(parent.toString())
              .setExecution(
                  Execution.newBuilder().setArgument("{\"searchTerm\":\"Cloud\"}").build())
              .build();

      Execution executionCreated = executionsClient.createExecution(executionRequest);

      System.out.println("Created execution: " + executionCreated.getName());

      // Wait for execution to finish using exponential backoff
      long backoffDelay = 1_000;
      Execution execution;
      System.out.println("Poll for result...");
      while (true) {
        execution = executionsClient.getExecution(executionCreated.getName());

        // Check if execution finished
        if (execution.getState() != Execution.State.ACTIVE) {
          break;
        }

        // Wait using exponential backoff
        System.out.println("- Waiting for results...");
        Thread.sleep(backoffDelay);
        backoffDelay *= 2;
      }

      System.out.println("Execution finished with state: " + execution.getState().name());
      System.out.println("Execution results: " + execution.getResult());
    }
  }
}

Node.js

// Execute workflow
try {
  const createExecutionRes = await client.createExecution({
    parent: client.workflowPath(projectId, location, workflow),
    execution: {
      argument: JSON.stringify({"searchTerm": "Friday"})
    }
});
const executionName = createExecutionRes[0].name;

Python

import time

from google.cloud import workflows_v1
from google.cloud.workflows import executions_v1

from google.cloud.workflows.executions_v1.types import executions

# TODO(developer): Update and uncomment the following lines.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"  # For example: us-central1
# workflow_id = "YOUR_WORKFLOW_ID"  # For example: myFirstWorkflow

# Initialize API clients.
execution_client = executions_v1.ExecutionsClient()
workflows_client = workflows_v1.WorkflowsClient()

# Construct the fully qualified location path.
parent = workflows_client.workflow_path(project_id, location, workflow_id)

# Execute the workflow adding an dictionary of arguments.
# Find more information about the Execution object here:
# https://cloud.google.com/python/docs/reference/workflows/latest/google.cloud.workflows.executions_v1.types.Execution
execution = executions_v1.Execution(
    name=parent,
    argument='{"searchTerm": "Cloud"}',
)

response = execution_client.create_execution(
    parent=parent,
    execution=execution,
)
print(f"Created execution: {response.name}")

# Wait for execution to finish, then print results.
execution_finished = False
backoff_delay = 1  # Start wait with delay of 1 second.
print("Poll for result...")

# Keep polling the state until the execution finishes,
# using exponential backoff.
while not execution_finished:
    execution = execution_client.get_execution(
        request={"name": response.name}
    )
    execution_finished = execution.state != executions.Execution.State.ACTIVE

    # If we haven't seen the result yet, keep waiting.
    if not execution_finished:
        print("- Waiting for results...")
        time.sleep(backoff_delay)
        # Double the delay to provide exponential backoff.
        backoff_delay *= 2
    else:
        print(f"Execution finished with state: {execution.state.name}")
        print(f"Execution results: {execution.result}")

如要進一步瞭解如何傳遞執行階段引數,請參閱「在執行要求中傳遞執行階段引數」。

清除所用資源

為了避免系統向您的 Google Cloud 帳戶收取本頁面所用資源的費用,請刪除含有這些資源的 Google Cloud 專案。

  1. 刪除您建立的工作流程:

    gcloud workflows delete myFirstWorkflow
    
  2. 系統詢問您是否要繼續時,請輸入 y

工作流程已刪除。

後續步驟