Delay Google Cloud Function

How to make event-triggered Cloud Function to pause while running?

Assuming you absolutely need this and you will not use this in production, this should be pretty straightforward if this is an asynchronous function.

Just define an async function that will return after an arbitrary amount of time:

async function sleepMS(timeMS) {
await new Promise(res => setTimeout(res, timeMS))
}

then after all your code runs and before your function returns, call it with the amount of time you wish

await sleepMS(20 * 1000)

Google Cloud Functions & PubSub - delay after idling

Reason is the Google Cloud Function is downing the instance after response sent.

Just change asynchronous publishing to synchronous and send response after success publish. It shortens publication timing to tens of milliseconds.

"use strict";
const PubSub = require("@google-cloud/pubsub");
const pubsub = PubSub({
projectId: "pubsub-forwarders"
});

exports.testFunction = async function testFunction(req, res) {
const messageId = await publishMessage("testtopic", "testmessage");
console.log("Message ", messageId, " published.");
res.status(200).send();
}

async function publishMessage(topicName, data) {
const topic = pubsub.topic(topicName);
const publisher = topic.publisher();
const dataBuffer = Buffer.from(data);
return await publisher.publish(dataBuffer);
}

See the reference: https://cloud.google.com/functions/docs/bestpractices/tips#do_not_start_background_activities

Executing cloud functions after n seconds on demand

You can use Cloud Tasks to schedule a delayed call back to a Cloud Function.



Related Topics



Leave a reply



Submit