Skip to content

Commit 28bf828

Browse files
committed
chore: update tasks example
1 parent 3ad5130 commit 28bf828

File tree

1 file changed

+51
-2
lines changed
  • samples/basic_tasks/functions

1 file changed

+51
-2
lines changed

samples/basic_tasks/functions/main.py

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
"""Firebase Cloud Functions for Tasks."""
2+
3+
import datetime
4+
import json
5+
26
from firebase_admin import initialize_app
3-
from firebase_functions import tasks_fn
7+
from google.cloud import tasks_v2
8+
from firebase_functions import tasks_fn, https_fn
49
from firebase_functions.options import SupportedRegion, RetryConfig, RateLimits
510

611
app = initialize_app()
712

813

914
# Once this function is deployed, a Task Queue will be created with the name
10-
# `ontaskdispatchedexample`.
15+
# `on_task_dispatched_example`. You can then enqueue tasks to this queue by
16+
# calling the `enqueue_task` function.
1117
@tasks_fn.on_task_dispatched(
1218
retry_config=RetryConfig(max_attempts=5),
1319
rate_limits=RateLimits(max_concurrent_dispatches=10),
@@ -18,3 +24,46 @@ def ontaskdispatchedexample(req: tasks_fn.CallableRequest):
1824
The endpoint which will be executed by the enqueued task.
1925
"""
2026
print(req.data)
27+
28+
29+
# To enqueue a task, you can use the following function.
30+
# e.g.
31+
# curl -X POST -H "Content-Type: application/json" \
32+
# -d '{"data": "Hello World!"}' \
33+
# https://enqueue-task-<projectHash>-<region>.a.run.app\
34+
@https_fn.on_request()
35+
def enqueuetask(req: https_fn.Request) -> https_fn.Response:
36+
"""
37+
Enqueues a task to the queue `on_task_dispatched_function`.
38+
"""
39+
client = tasks_v2.CloudTasksClient()
40+
41+
# The URL of the `on_task_dispatched_function` function.
42+
# Must be set to the URL of the deployed function.
43+
44+
url = req.json.get("url") if req.json else None
45+
46+
body = {"data": req.json}
47+
48+
task: tasks_v2.Task = tasks_v2.Task(
49+
**{
50+
"http_request": {
51+
"http_method": tasks_v2.HttpMethod.POST,
52+
"url": url,
53+
"headers": {
54+
"Content-type": "application/json"
55+
},
56+
"body": json.dumps(body).encode(),
57+
},
58+
"schedule_time":
59+
datetime.datetime.utcnow() + datetime.timedelta(minutes=1),
60+
})
61+
62+
parent = client.queue_path(
63+
app.project_id,
64+
SupportedRegion.US_CENTRAL1,
65+
"ontaskdispatchedexample2",
66+
)
67+
68+
client.create_task(request={"parent": parent, "task": task})
69+
return https_fn.Response("Task enqueued.")

0 commit comments

Comments
 (0)