0

I have a google cloud function in which I initialize some variables on running the function for the first time so that response will be fast from the next time. The variable values lost when I don't use the function for a certain amount of time which means the function is not running when it's not in use. How can I prevent this?

var browser;
var page;

function getBrowserPage() {
    return new Promise(async (resolve, reject) => {
        if (!browser) {
            browser = await puppeteer.launch({ args: ['--no-sandbox'] });
            console.log('Creating a new browser...');
        }
        if (!page) {
            page = await browser.newPage();
            console.log('Creating a new page...');
        }
        resolve(page);
    });
}

await getBrowserPage().then(p => { 
console.log('page created')
 }).catch(err => {
 console.log(err) 
});

1 Answers1

0

Trigger a CRON job (via Cloud Scheduler) to invoke your function every few minutes and thus force it to stay warm.

Ideally you'd also like to add handling to your function so that warming/pinging invocations are terminated ASAP; in your case for example we don't want to launch Puppeteer every few minutes for nothing.

Here's a sample implementation in AWS Lambda.

Aleksi
  • 4,483
  • 33
  • 45
  • 2
    This is not going to be 100% effective. Please see the marked duplicate for an explanation why it's not possible to force a function to stay warm. – Doug Stevenson Aug 26 '19 at 11:47