CondorW
CondorW

Reputation: 217

Periodically run a cloud function every second without client input

I am working on an app, where I need to periodically (every second) need to write a new timestamp in a field in firestore, this write should be performed when a specific property of the document equals true, if not the periodic execution should stop - how can I do that?

Upvotes: 3

Views: 3129

Answers (3)

Ruan
Ruan

Reputation: 4293

You can solve this issue by doing the following

  1. Create a cloud function that runs every minute
  2. Add in 4 timers that executes every 15 seconds

NOTE: Depending on you logic this might cost you... Don't do this without understanding what your usage costs will be, and don't forget about it. I take no responsibility for servers catching fire with this.

   export const my15SecondTimer = functions.pubsub
   .schedule("* * * * *")
   .onRun(async (context) => {
   
    // Some logic (1)
    setTimeout(async () => {
     // Some logic (2)
    }, 15000);

   setTimeout(async () => {
     // Some logic (3)
    }, 3000);
 
   setTimeout(async () => {
     // Some logic (4)
    }, 4500);
   
   });

Upvotes: 1

guillaume blaquiere
guillaume blaquiere

Reputation: 76018

The easiest solution I can offer is to use Cloud Task. When a user create a session, create a dedicated task queue with a rate limit of 1 per seconds and a bunch of task in that queues (for instance 3600 task per hour).

That task will trigger a HTTP endpoint (typically a Cloud Functions or a Cloud Run endpoint) that will increment the counter.


The main question that I had was about the firestore choice. As far as I understand, if you have 10 users in parallel, you have 10 counter and you write 10 times the same thing in firestore. not really efficient.

I have 2 propositions here:

  1. Can you use a single counter and have several user object using the same count down?
  2. Did you consider Cloud Memorystore to use in memory database to perform your per-user-timestamp-write and save only the result in Firestore document.

Upvotes: 1

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

As you see here in the doc, the maximum execution frequency for scheduled Cloud Functions is one execution per minute.

Since you need a higher frequency, you cannot fulfill your requirement with only a Cloud Function. You'll need to use another approach.

Upvotes: 0

Related Questions