rahulserver
rahulserver

Reputation: 11205

Firebase/google cloud functions time based trigger prevent concurrent executions

I have a firebase function that runs every 2 minutes. The problem is that sometimes it takes over 540sec. to finish. Hence two executions of the function occur which messes up things. Is there a way to ensure that the function does not fire till a previous instance finishes?

I tried to handle it using a flag stored in firestore which was set to true when function would start running, and false when function would finish. However sometimes function execution times out hence the flag is never set to false, thereby stopping all future executions.

So how do I make sure that only one execution of the function is running at a time?

Upvotes: 0

Views: 79

Answers (2)

RobLjm
RobLjm

Reputation: 429

You can limit the number of instances using the runWith method and using the maxInstances parameter. Read more here.

By the way, why are your functions taking too long to execute? are you terminating them correctly? You can post relevant part of you code so we can see why or you can learn about how to terminate your function here

Upvotes: 2

Dharmaraj
Dharmaraj

Reputation: 50860

Is there a way to ensure that the function does not fire till a previous instance finishes?

No. You'll have to store some value in a database as you are doing now and terminate the function if an instance is active.

However sometimes function execution times out hence the flag is never set to false, thereby stopping all future executions.

Checkout Cloud Functions V2 (beta) or Cloud Run itself that can run up to 1 hour.

Also, if you know a function execution is going to take more than 540 seconds every time, it might be best to increase the interval between 2 invocations.

Upvotes: 1

Related Questions