Google Cloud Tasks V2 Client - Class CloudTasksClient (1.11.11)

Reference documentation and code samples for the Google Cloud Tasks V2 Client class CloudTasksClient.

Service Description: Cloud Tasks allows developers to manage the execution of background work in their applications.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:

$cloudTasksClient = new CloudTasksClient();
try {
    $formattedParent = $cloudTasksClient->locationName('[PROJECT]', '[LOCATION]');
    $queue = new Queue();
    $response = $cloudTasksClient->createQueue($formattedParent, $queue);
} finally {
    $cloudTasksClient->close();
}

Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.

Methods

locationName

Formats a string containing the fully-qualified path to represent a location resource.

Parameters
NameDescription
project string
location string
Returns
TypeDescription
stringThe formatted location resource.

queueName

Formats a string containing the fully-qualified path to represent a queue resource.

Parameters
NameDescription
project string
location string
queue string
Returns
TypeDescription
stringThe formatted queue resource.

taskName

Formats a string containing the fully-qualified path to represent a task resource.

Parameters
NameDescription
project string
location string
queue string
task string
Returns
TypeDescription
stringThe formatted task resource.

projectName

Formats a string containing the fully-qualified path to represent a project resource.

Parameter
NameDescription
project string
Returns
TypeDescription
stringThe formatted project resource.

parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • location: projects/{project}/locations/{location}
  • queue: projects/{project}/locations/{location}/queues/{queue}
  • task: projects/{project}/locations/{location}/queues/{queue}/tasks/{task}

The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.

Parameters
NameDescription
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
TypeDescription
arrayAn associative array from name component IDs to component values.

__construct

Constructor.

Parameters
NameDescription
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage: In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.

↳ transport string|TransportInterface

The transport used for executing network requests. May be either the string rest or grpc. Defaults to grpc if gRPC support is detected on the system. Advanced usage: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.

createQueue

Creates a queue.

Queues created with this method allow tasks to live for a maximum of 31 days. After a task is 31 days old, the task will be deleted regardless of whether it was dispatched or not.

WARNING: Using this method may have unintended side effects if you are using an App Engine queue.yaml or queue.xml file to manage your queues. Read Overview of Queue Management and queue.yaml before using this method.

Parameters
NameDescription
parent string

Required. The location name in which the queue will be created. For example: projects/PROJECT_ID/locations/LOCATION_ID

The list of allowed locations can be obtained by calling Cloud Tasks' implementation of ListLocations.

queue Google\Cloud\Tasks\V2\Queue

Required. The queue to create.

Queue's name cannot be the same as an existing queue.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedParent The location name in which the queue will be created.
 *                                For example: `projects/PROJECT_ID/locations/LOCATION_ID`
 *
 *                                The list of allowed locations can be obtained by calling Cloud
 *                                Tasks' implementation of
 *                                [ListLocations][google.cloud.location.Locations.ListLocations]. Please see
 *                                {@see CloudTasksClient::locationName()} for help formatting this field.
 */
function create_queue_sample(string $formattedParent): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $queue = new Queue();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->createQueue($formattedParent, $queue);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudTasksClient::locationName('[PROJECT]', '[LOCATION]');

    create_queue_sample($formattedParent);
}

createTask

Creates a task and adds it to a queue.

Tasks cannot be updated after creation; there is no UpdateTask command.

  • The maximum task size is 100KB.
Parameters
NameDescription
parent string

Required. The queue name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID

The queue must already exist.

task Google\Cloud\Tasks\V2\Task

Required. The task to add.

Task names have the following format: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID. The user can optionally specify a task name. If a name is not specified then the system will generate a random unique task id, which will be set in the task returned in the response.

If schedule_time is not set or is in the past then Cloud Tasks will set it to the current time.

Task De-duplication:

Explicitly specifying a task ID enables task de-duplication. If a task's ID is identical to that of an existing task or a task that was deleted or executed recently then the call will fail with ALREADY_EXISTS. If the task's queue was created using Cloud Tasks, then another task with the same name can't be created for ~1hour after the original task was deleted or executed. If the task's queue was created using queue.yaml or queue.xml, then another task with the same name can't be created for ~9days after the original task was deleted or executed.

Because there is an extra lookup cost to identify duplicate task names, these CreateTask calls have significantly increased latency. Using hashed strings for the task id or for the prefix of the task id is recommended. Choosing task ids that are sequential or have sequential prefixes, for example using a timestamp, causes an increase in latency and error rates in all task commands. The infrastructure relies on an approximately uniform distribution of task ids to store and serve tasks efficiently.

optionalArgs array

Optional.

↳ responseView int

The response_view specifies which subset of the Task will be returned. By default response_view is BASIC; not all information is retrieved by default because some data, such as payloads, might be desirable to return only when needed because of its large size or because of the sensitivity of data that it contains. Authorization for FULL requires cloudtasks.tasks.fullView Google IAM permission on the Task resource. For allowed values, use constants defined on Google\Cloud\Tasks\V2\Task\View

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Task
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Task;

/**
 * @param string $formattedParent The queue name. For example:
 *                                `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`
 *
 *                                The queue must already exist. Please see
 *                                {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function create_task_sample(string $formattedParent): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $task = new Task();

    // Call the API and handle any network failures.
    try {
        /** @var Task $response */
        $response = $cloudTasksClient->createTask($formattedParent, $task);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    create_task_sample($formattedParent);
}

deleteQueue

Deletes a queue.

This command will delete the queue even if it has tasks in it.

Note: If you delete a queue, a queue with the same name can't be created for 7 days.

WARNING: Using this method may have unintended side effects if you are using an App Engine queue.yaml or queue.xml file to manage your queues. Read Overview of Queue Management and queue.yaml before using this method.

Parameters
NameDescription
name string

Required. The queue name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;

/**
 * @param string $formattedName The queue name. For example:
 *                              `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`
 *                              Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function delete_queue_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        $cloudTasksClient->deleteQueue($formattedName);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    delete_queue_sample($formattedName);
}

deleteTask

Deletes a task.

A task can be deleted if it is scheduled or dispatched. A task cannot be deleted if it has executed successfully or permanently failed.

Parameters
NameDescription
name string

Required. The task name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;

/**
 * @param string $formattedName The task name. For example:
 *                              `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
 *                              Please see {@see CloudTasksClient::taskName()} for help formatting this field.
 */
function delete_task_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        $cloudTasksClient->deleteTask($formattedName);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::taskName('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]');

    delete_task_sample($formattedName);
}

getIamPolicy

Gets the access control policy for a Queue.

Returns an empty policy if the resource exists and does not have a policy set.

Authorization requires the following Google IAM permission on the specified resource parent:

  • cloudtasks.queues.getIamPolicy
Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.

optionalArgs array

Optional.

↳ options GetPolicyOptions

OPTIONAL: A GetPolicyOptions object for specifying options to GetIamPolicy.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\Policy
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Tasks\V2\CloudTasksClient;

/**
 * @param string $resource REQUIRED: The resource for which the policy is being requested.
 *                         See the operation documentation for the appropriate value for this field.
 */
function get_iam_policy_sample(string $resource): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Policy $response */
        $response = $cloudTasksClient->getIamPolicy($resource);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';

    get_iam_policy_sample($resource);
}

getQueue

Gets a queue.

Parameters
NameDescription
name string

Required. The resource name of the queue. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedName The resource name of the queue. For example:
 *                              `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`
 *                              Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function get_queue_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->getQueue($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    get_queue_sample($formattedName);
}

getTask

Gets a task.

Parameters
NameDescription
name string

Required. The task name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID

optionalArgs array

Optional.

↳ responseView int

The response_view specifies which subset of the Task will be returned. By default response_view is BASIC; not all information is retrieved by default because some data, such as payloads, might be desirable to return only when needed because of its large size or because of the sensitivity of data that it contains. Authorization for FULL requires cloudtasks.tasks.fullView Google IAM permission on the Task resource. For allowed values, use constants defined on Google\Cloud\Tasks\V2\Task\View

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Task
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Task;

/**
 * @param string $formattedName The task name. For example:
 *                              `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
 *                              Please see {@see CloudTasksClient::taskName()} for help formatting this field.
 */
function get_task_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Task $response */
        $response = $cloudTasksClient->getTask($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::taskName('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]');

    get_task_sample($formattedName);
}

listQueues

Lists queues.

Queues are returned in lexicographical order.

Parameters
NameDescription
parent string

Required. The location name. For example: projects/PROJECT_ID/locations/LOCATION_ID

optionalArgs array

Optional.

↳ filter string

filter can be used to specify a subset of queues. Any Queue field can be used as a filter and several operators as supported. For example: <=, <, >=, >, !=, =, :. The filter syntax is the same as described in Stackdriver's Advanced Logs Filters. Sample filter "state: PAUSED". Note that using filters might cause fewer queues than the requested page_size to be returned.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedParent The location name.
 *                                For example: `projects/PROJECT_ID/locations/LOCATION_ID`
 *                                Please see {@see CloudTasksClient::locationName()} for help formatting this field.
 */
function list_queues_sample(string $formattedParent): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $cloudTasksClient->listQueues($formattedParent);

        /** @var Queue $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudTasksClient::locationName('[PROJECT]', '[LOCATION]');

    list_queues_sample($formattedParent);
}

listTasks

Lists the tasks in a queue.

By default, only the BASIC view is retrieved due to performance considerations; response_view controls the subset of information which is returned.

The tasks may be returned in any order. The ordering may change at any time.

Parameters
NameDescription
parent string

Required. The queue name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ responseView int

The response_view specifies which subset of the Task will be returned. By default response_view is BASIC; not all information is retrieved by default because some data, such as payloads, might be desirable to return only when needed because of its large size or because of the sensitivity of data that it contains. Authorization for FULL requires cloudtasks.tasks.fullView Google IAM permission on the Task resource. For allowed values, use constants defined on Google\Cloud\Tasks\V2\Task\View

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Task;

/**
 * @param string $formattedParent The queue name. For example:
 *                                `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`
 *                                Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function list_tasks_sample(string $formattedParent): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $cloudTasksClient->listTasks($formattedParent);

        /** @var Task $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    list_tasks_sample($formattedParent);
}

pauseQueue

Pauses the queue.

If a queue is paused then the system will stop dispatching tasks until the queue is resumed via ResumeQueue. Tasks can still be added when the queue is paused. A queue is paused if its state is PAUSED.

Parameters
NameDescription
name string

Required. The queue name. For example: projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedName The queue name. For example:
 *                              `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`
 *                              Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function pause_queue_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->pauseQueue($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    pause_queue_sample($formattedName);
}

purgeQueue

Purges a queue by deleting all of its tasks.

All tasks created before this method is called are permanently deleted.

Purge operations can take up to one minute to take effect. Tasks might be dispatched before the purge takes effect. A purge is irreversible.

Parameters
NameDescription
name string

Required. The queue name. For example: projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedName The queue name. For example:
 *                              `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`
 *                              Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function purge_queue_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->purgeQueue($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    purge_queue_sample($formattedName);
}

resumeQueue

Resume a queue.

This method resumes a queue after it has been PAUSED or DISABLED. The state of a queue is stored in the queue's state; after calling this method it will be set to RUNNING.

WARNING: Resuming many high-QPS queues at the same time can lead to target overloading. If you are resuming high-QPS queues, follow the 500/50/5 pattern described in Managing Cloud Tasks Scaling Risks.

Parameters
NameDescription
name string

Required. The queue name. For example: projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * @param string $formattedName The queue name. For example:
 *                              `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`
 *                              Please see {@see CloudTasksClient::queueName()} for help formatting this field.
 */
function resume_queue_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->resumeQueue($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');

    resume_queue_sample($formattedName);
}

runTask

Forces a task to run now.

When this method is called, Cloud Tasks will dispatch the task, even if the task is already running, the queue has reached its RateLimits or is PAUSED.

This command is meant to be used for manual debugging. For example, RunTask can be used to retry a failed task after a fix has been made or to manually force a task to be dispatched now.

The dispatched task is returned. That is, the task that is returned contains the status after the task is dispatched but before the task is received by its target.

If Cloud Tasks receives a successful response from the task's target, then the task will be deleted; otherwise the task's schedule_time will be reset to the time that RunTask was called plus the retry delay specified in the queue's RetryConfig.

RunTask returns NOT_FOUND when it is called on a task that has already succeeded or permanently failed.

Parameters
NameDescription
name string

Required. The task name. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID

optionalArgs array

Optional.

↳ responseView int

The response_view specifies which subset of the Task will be returned. By default response_view is BASIC; not all information is retrieved by default because some data, such as payloads, might be desirable to return only when needed because of its large size or because of the sensitivity of data that it contains. Authorization for FULL requires cloudtasks.tasks.fullView Google IAM permission on the Task resource. For allowed values, use constants defined on Google\Cloud\Tasks\V2\Task\View

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Task
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Task;

/**
 * @param string $formattedName The task name. For example:
 *                              `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
 *                              Please see {@see CloudTasksClient::taskName()} for help formatting this field.
 */
function run_task_sample(string $formattedName): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Call the API and handle any network failures.
    try {
        /** @var Task $response */
        $response = $cloudTasksClient->runTask($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = CloudTasksClient::taskName('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]');

    run_task_sample($formattedName);
}

setIamPolicy

Sets the access control policy for a Queue. Replaces any existing policy.

Note: The Cloud Console does not check queue-level IAM permissions yet. Project-level permissions are required to use the Cloud Console.

Authorization requires the following Google IAM permission on the specified resource parent:

  • cloudtasks.queues.setIamPolicy
Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.

policy Google\Cloud\Iam\V1\Policy

REQUIRED: The complete policy to be applied to the resource. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them.

optionalArgs array

Optional.

↳ updateMask FieldMask

OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: paths: "bindings, etag"

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\Policy
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Tasks\V2\CloudTasksClient;

/**
 * @param string $resource REQUIRED: The resource for which the policy is being specified.
 *                         See the operation documentation for the appropriate value for this field.
 */
function set_iam_policy_sample(string $resource): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $policy = new Policy();

    // Call the API and handle any network failures.
    try {
        /** @var Policy $response */
        $response = $cloudTasksClient->setIamPolicy($resource, $policy);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';

    set_iam_policy_sample($resource);
}

testIamPermissions

Returns permissions that a caller has on a Queue.

If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.

Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.

Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.

permissions string[]

The set of permissions to check for the resource. Permissions with wildcards (such as '' or 'storage.') are not allowed. For more information see IAM Overview.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\TestIamPermissionsResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\TestIamPermissionsResponse;
use Google\Cloud\Tasks\V2\CloudTasksClient;

/**
 * @param string $resource           REQUIRED: The resource for which the policy detail is being requested.
 *                                   See the operation documentation for the appropriate value for this field.
 * @param string $permissionsElement The set of permissions to check for the `resource`. Permissions with
 *                                   wildcards (such as '*' or 'storage.*') are not allowed. For more
 *                                   information see
 *                                   [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
 */
function test_iam_permissions_sample(string $resource, string $permissionsElement): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $permissions = [$permissionsElement,];

    // Call the API and handle any network failures.
    try {
        /** @var TestIamPermissionsResponse $response */
        $response = $cloudTasksClient->testIamPermissions($resource, $permissions);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';
    $permissionsElement = '[PERMISSIONS]';

    test_iam_permissions_sample($resource, $permissionsElement);
}

updateQueue

Updates a queue.

This method creates the queue if it does not exist and updates the queue if it does exist.

Queues created with this method allow tasks to live for a maximum of 31 days. After a task is 31 days old, the task will be deleted regardless of whether it was dispatched or not.

WARNING: Using this method may have unintended side effects if you are using an App Engine queue.yaml or queue.xml file to manage your queues. Read Overview of Queue Management and queue.yaml before using this method.

Parameters
NameDescription
queue Google\Cloud\Tasks\V2\Queue

Required. The queue to create or update.

The queue's name must be specified.

Output only fields cannot be modified using UpdateQueue. Any value specified for an output only field will be ignored. The queue's name cannot be changed.

optionalArgs array

Optional.

↳ updateMask FieldMask

A mask used to specify which fields of the queue are being updated. If empty, then all fields will be updated.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Tasks\V2\Queue
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function update_queue_sample(): void
{
    // Create a client.
    $cloudTasksClient = new CloudTasksClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $queue = new Queue();

    // Call the API and handle any network failures.
    try {
        /** @var Queue $response */
        $response = $cloudTasksClient->updateQueue($queue);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

Constants

SERVICE_NAME

Value: 'google.cloud.tasks.v2.CloudTasks'

The name of the service.

SERVICE_ADDRESS

Value: 'cloudtasks.googleapis.com'

The default address of the service.

DEFAULT_SERVICE_PORT

Value: 443

The default port of the service.

CODEGEN_NAME

Value: 'gapic'

The name of the code generator, to be included in the agent header.