1
1
"""Firebase Cloud Functions for Tasks."""
2
+
3
+ import datetime
4
+ import json
5
+
2
6
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
4
9
from firebase_functions .options import SupportedRegion , RetryConfig , RateLimits
5
10
6
11
app = initialize_app ()
7
12
8
13
9
14
# 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.
11
17
@tasks_fn .on_task_dispatched (
12
18
retry_config = RetryConfig (max_attempts = 5 ),
13
19
rate_limits = RateLimits (max_concurrent_dispatches = 10 ),
@@ -18,3 +24,46 @@ def ontaskdispatchedexample(req: tasks_fn.CallableRequest):
18
24
The endpoint which will be executed by the enqueued task.
19
25
"""
20
26
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