0
# Task Management
1
2
Task lifecycle operations for creating, monitoring, and executing distributed work units. Tasks can target HTTP endpoints or App Engine applications with configurable scheduling, authentication, and retry behavior.
3
4
## Capabilities
5
6
### Task Listing
7
8
Retrieve tasks within a queue with optional filtering, view control, and pagination support.
9
10
```python { .api }
11
def list_tasks(
12
self,
13
request: Union[ListTasksRequest, dict] = None,
14
*,
15
parent: str = None,
16
retry: OptionalRetry = DEFAULT,
17
timeout: float = DEFAULT,
18
metadata: Sequence[Tuple[str, str]] = ()
19
) -> pagers.ListTasksPager:
20
"""List the tasks in a queue.
21
22
Args:
23
request: The request object or dictionary.
24
parent: Required. The queue name (projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID).
25
retry: Designation of what errors should be retried.
26
timeout: The timeout for this request.
27
metadata: Strings which should be sent along with the request as metadata.
28
29
Returns:
30
An iterable of Task resources.
31
"""
32
```
33
34
### Task Retrieval
35
36
Get detailed information about a specific task including execution status and attempt history.
37
38
```python { .api }
39
def get_task(
40
self,
41
request: Union[GetTaskRequest, dict] = None,
42
*,
43
name: str = None,
44
retry: OptionalRetry = DEFAULT,
45
timeout: float = DEFAULT,
46
metadata: Sequence[Tuple[str, str]] = ()
47
) -> Task:
48
"""Get a task.
49
50
Args:
51
request: The request object or dictionary.
52
name: Required. The task name.
53
retry: Designation of what errors should be retried.
54
timeout: The timeout for this request.
55
metadata: Strings which should be sent along with the request as metadata.
56
57
Returns:
58
The task object.
59
"""
60
```
61
62
### Task Creation
63
64
Create new tasks with HTTP or App Engine targets, optional scheduling, and authentication configuration.
65
66
```python { .api }
67
def create_task(
68
self,
69
request: Union[CreateTaskRequest, dict] = None,
70
*,
71
parent: str = None,
72
task: Task = None,
73
retry: OptionalRetry = DEFAULT,
74
timeout: float = DEFAULT,
75
metadata: Sequence[Tuple[str, str]] = ()
76
) -> Task:
77
"""Create a task and add it to a queue.
78
79
Args:
80
request: The request object or dictionary.
81
parent: Required. The queue name where the task will be created.
82
task: Required. The task to add.
83
retry: Designation of what errors should be retried.
84
timeout: The timeout for this request.
85
metadata: Strings which should be sent along with the request as metadata.
86
87
Returns:
88
The created task.
89
"""
90
```
91
92
### Task Deletion
93
94
Remove tasks from queues, canceling their execution.
95
96
```python { .api }
97
def delete_task(
98
self,
99
request: Union[DeleteTaskRequest, dict] = None,
100
*,
101
name: str = None,
102
retry: OptionalRetry = DEFAULT,
103
timeout: float = DEFAULT,
104
metadata: Sequence[Tuple[str, str]] = ()
105
) -> None:
106
"""Delete a task.
107
108
Args:
109
request: The request object or dictionary.
110
name: Required. The task name to delete.
111
retry: Designation of what errors should be retried.
112
timeout: The timeout for this request.
113
metadata: Strings which should be sent along with the request as metadata.
114
"""
115
```
116
117
### Task Execution
118
119
Force immediate execution of queued tasks for testing or manual processing.
120
121
```python { .api }
122
def run_task(
123
self,
124
request: Union[RunTaskRequest, dict] = None,
125
*,
126
name: str = None,
127
retry: OptionalRetry = DEFAULT,
128
timeout: float = DEFAULT,
129
metadata: Sequence[Tuple[str, str]] = ()
130
) -> Task:
131
"""Force a task to run immediately.
132
133
Args:
134
request: The request object or dictionary.
135
name: Required. The task name to run.
136
retry: Designation of what errors should be retried.
137
timeout: The timeout for this request.
138
metadata: Strings which should be sent along with the request as metadata.
139
140
Returns:
141
The task after execution attempt.
142
"""
143
```
144
145
## Request Types
146
147
### ListTasksRequest
148
```python { .api }
149
class ListTasksRequest:
150
parent: str # Required. The queue name
151
response_view: Task.View # Specifies which subset of Task to return
152
page_size: int # Maximum page size (max 1000)
153
page_token: str # Token for pagination
154
```
155
156
### GetTaskRequest
157
```python { .api }
158
class GetTaskRequest:
159
name: str # Required. The task name
160
response_view: Task.View # Specifies which subset of Task to return
161
```
162
163
### CreateTaskRequest
164
```python { .api }
165
class CreateTaskRequest:
166
parent: str # Required. The queue name where task will be created
167
task: Task # Required. The task to add
168
response_view: Task.View # Specifies which subset of Task to return
169
```
170
171
### DeleteTaskRequest
172
```python { .api }
173
class DeleteTaskRequest:
174
name: str # Required. The task name to delete
175
```
176
177
### RunTaskRequest
178
```python { .api }
179
class RunTaskRequest:
180
name: str # Required. The task name to run
181
response_view: Task.View # Specifies which subset of Task to return
182
```
183
184
### ListTasksResponse
185
```python { .api }
186
class ListTasksResponse:
187
tasks: MutableSequence[Task] # List of tasks
188
next_page_token: str # Token for next page
189
```
190
191
## Task Structure
192
193
### Task
194
```python { .api }
195
class Task:
196
name: str # Optionally caller-specified task name
197
app_engine_http_request: AppEngineHttpRequest # App Engine HTTP request (oneof)
198
http_request: HttpRequest # HTTP request to worker (oneof)
199
schedule_time: timestamp_pb2.Timestamp # When task is scheduled to be attempted
200
create_time: timestamp_pb2.Timestamp # Output only creation time
201
dispatch_deadline: duration_pb2.Duration # Deadline for requests sent to worker
202
dispatch_count: int # Output only number of attempts dispatched
203
response_count: int # Output only number of attempts that received response
204
first_attempt: Attempt # Output only status of first attempt
205
last_attempt: Attempt # Output only status of last attempt
206
view: Task.View # Output only view specifying returned subset
207
208
class View:
209
VIEW_UNSPECIFIED = 0 # Unspecified, defaults to BASIC
210
BASIC = 1 # Basic view omits large/sensitive fields
211
FULL = 2 # All information returned (requires IAM permission)
212
```
213
214
### Attempt
215
```python { .api }
216
class Attempt:
217
schedule_time: timestamp_pb2.Timestamp # Output only time attempt was scheduled
218
dispatch_time: timestamp_pb2.Timestamp # Output only time attempt was dispatched
219
response_time: timestamp_pb2.Timestamp # Output only time response was received
220
response_status: status_pb2.Status # Output only response from worker
221
```
222
223
## Usage Examples
224
225
### Creating HTTP Tasks
226
227
```python
228
from google.cloud import tasks
229
import json
230
231
client = tasks.CloudTasksClient()
232
233
# Define paths
234
project = 'my-project-id'
235
location = 'us-central1'
236
queue_name = 'my-queue'
237
238
queue_path = client.queue_path(project, location, queue_name)
239
240
# Create an HTTP task
241
task_data = {'user_id': 123, 'action': 'process_order'}
242
task = tasks.Task(
243
http_request=tasks.HttpRequest(
244
url='https://myapp.com/process',
245
http_method=tasks.HttpMethod.POST,
246
headers={'Content-Type': 'application/json'},
247
body=json.dumps(task_data).encode('utf-8')
248
)
249
)
250
251
# Add the task to the queue
252
created_task = client.create_task(parent=queue_path, task=task)
253
print(f'Created task: {created_task.name}')
254
```
255
256
### Creating Scheduled Tasks
257
258
```python
259
from google.cloud import tasks
260
from google.protobuf import timestamp_pb2
261
import datetime
262
263
client = tasks.CloudTasksClient()
264
queue_path = client.queue_path('my-project-id', 'us-central1', 'my-queue')
265
266
# Schedule task for 10 minutes from now
267
schedule_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
268
timestamp = timestamp_pb2.Timestamp()
269
timestamp.FromDatetime(schedule_time)
270
271
task = tasks.Task(
272
http_request=tasks.HttpRequest(
273
url='https://myapp.com/scheduled-job',
274
http_method=tasks.HttpMethod.POST
275
),
276
schedule_time=timestamp
277
)
278
279
created_task = client.create_task(parent=queue_path, task=task)
280
print(f'Scheduled task: {created_task.name} for {schedule_time}')
281
```
282
283
### Creating App Engine Tasks
284
285
```python
286
from google.cloud import tasks
287
288
client = tasks.CloudTasksClient()
289
queue_path = client.queue_path('my-project-id', 'us-central1', 'my-queue')
290
291
# Create an App Engine task
292
task = tasks.Task(
293
app_engine_http_request=tasks.AppEngineHttpRequest(
294
http_method=tasks.HttpMethod.POST,
295
relative_uri='/task-handler',
296
app_engine_routing=tasks.AppEngineRouting(
297
service='worker',
298
version='v1'
299
),
300
body=b'{"data": "example"}'
301
)
302
)
303
304
created_task = client.create_task(parent=queue_path, task=task)
305
print(f'Created App Engine task: {created_task.name}')
306
```
307
308
### Managing Task Lifecycle
309
310
```python
311
from google.cloud import tasks
312
313
client = tasks.CloudTasksClient()
314
queue_path = client.queue_path('my-project-id', 'us-central1', 'my-queue')
315
316
# List tasks in queue
317
print("Tasks in queue:")
318
for task in client.list_tasks(parent=queue_path):
319
print(f'- {task.name}: {task.dispatch_count} dispatches')
320
321
# Get task details with full view
322
task_name = client.task_path('my-project-id', 'us-central1', 'my-queue', 'my-task')
323
task = client.get_task(
324
name=task_name,
325
response_view=tasks.Task.View.FULL
326
)
327
print(f'Task details: {task.create_time}, {task.schedule_time}')
328
329
# Force task execution
330
run_result = client.run_task(name=task_name)
331
print(f'Task run result: {run_result.dispatch_count}')
332
333
# Delete task
334
client.delete_task(name=task_name)
335
print(f'Deleted task: {task_name}')
336
```
337
338
### Authenticated HTTP Tasks
339
340
```python
341
from google.cloud import tasks
342
343
client = tasks.CloudTasksClient()
344
queue_path = client.queue_path('my-project-id', 'us-central1', 'my-queue')
345
346
# Create task with OAuth authentication
347
task = tasks.Task(
348
http_request=tasks.HttpRequest(
349
url='https://myapp.com/authenticated-endpoint',
350
http_method=tasks.HttpMethod.POST,
351
oauth_token=tasks.OAuthToken(
352
service_account_email='worker@my-project.iam.gserviceaccount.com',
353
scope='https://www.googleapis.com/auth/cloud-platform'
354
),
355
body=b'{"secure": "data"}'
356
)
357
)
358
359
created_task = client.create_task(parent=queue_path, task=task)
360
print(f'Created authenticated task: {created_task.name}')
361
362
# Create task with OIDC authentication
363
oidc_task = tasks.Task(
364
http_request=tasks.HttpRequest(
365
url='https://myapp.com/oidc-endpoint',
366
http_method=tasks.HttpMethod.POST,
367
oidc_token=tasks.OidcToken(
368
service_account_email='worker@my-project.iam.gserviceaccount.com',
369
audience='https://myapp.com'
370
)
371
)
372
)
373
374
created_oidc_task = client.create_task(parent=queue_path, task=oidc_task)
375
print(f'Created OIDC task: {created_oidc_task.name}')
376
```