I wish to run a scheduler which runs according to each user in my cloud functions and not universal scheduler which runs at the same time for all users.
For example, if a UserA performs a certain action the scheduler(eg. every 30 mins) is initiated for userA only and not other users.
But then UserB also performs that same action and initiates the scheduler for himself at a different time.
Now UserA’s and UserB’s scheduler could be running at different times but same intervals(30 mins)
How can I create such a function?
Help would be very much appreciated.
Cloud Functions alone won't be able to schedule function executions indepently for each user. You can only schedule a single function on a schedule that you provide in the function configuration. Obviously, it won't scale for you to deploy a new function for each user.
You have two choices:
Deploy a scheduled function that runs as frequently as possible (every 1 minute). Have it query a database to figure out which items of work need to be run per-user, and arrange for them to execute. Based on the volume of work, you might want to offload those to other function invocations via pubsub.
On a per-user basis, use Cloud Tasks to schedule the first item of work that should be done for the user (which could be implemented to invoke an HTTP trigger). The payload of the task should describe the work to be done (minimally it should contain the id of the user it represents). When that task completes, the HTTP trigger will have to figure out when the next periodic invocation should be, and schedule it as such. You will effectively always have one task in a queue "pending" execution. If somehow your function fails to establish the next task, then the periodic nature will break, and you will have to somehow have to figure out how to start it up again.
Option 1 is easier to implement, IMO, but you lose the granularity of timing if the invocation needs to happen precisely on the exact second of the minute. You will also need to maintain a database or some other store to query to figure out how to tell the per-minute function should do more work for any given user.
Option 2 is much harder to implement correctly, requires the use of a whole new product with a new API, but you will be able to schedule tasks with much finer granularity.
It looks you are looking for Cloud Tasks, I wrote a post about it, maybe it will help you
Using Cloud Tasks you can basically set a process to run a given time and manage any kind of functionality you need.
UPDATE:
Cloud Tasks allow you to pass a payload that you can use to calculate any subsequential tasks as needed, a few strategies would go as follows:
- Create (for example) N number tasks which 30 mints (or whatever interval you need).
- Create only one task and during the execution time decide if you need to create further tasks.
This is the initial strategy I would start with based on the information you provided.