Home > Mobile >  Code outside of cloud function is executed, occasionally
Code outside of cloud function is executed, occasionally

Time:10-26

I have a textbook Google Cloud Function as follows:

const fs = require("fs");

console.log("Here!");

exports.validateTemperature = async (req, res) => {
  console.log("There");
  // ...
};

It is triggered by Cloud Scheduler once every 15 minutes.

I expect the line Here! to be printed when the function is deployed. However, occasionally when the function is invoked, Here! is also printed, and sometimes it occurs after There is printed.

What is causing this behavior?

CodePudding user response:

Anything outside of the function scope falls in Global scope. That runs every time a new instance for the Cloud Function starts (popularly known as the cold start). It is mostly used to execute any time consuming tasks so they are executed only once per instance and not every function invocation. The value is shared across all invocations handled by that instance.

A simple example would reusing database connection instead of creating a new one every time as mentioned in this answer.

  • Related