我使用 setInterval 将 Firebase 函数设置为每 20 分钟运行一次,但它的执行频率比预期更高。以下是我的代码的相关部分:
try {
const response = await axios.get(
"https://ll.thespacedevs.com/2.0.0/event/upcoming/?limit=50&offset=0",
{ timeout: 90000 }
);
return response.data.results;
} catch (error) {
console.error("Error fetching space events:", error);
if (retryCount < 3) {
// Retry up to 3 times
const waitTime = 900000 * (retryCount + 1); // 15, 30, 45 minutes
console.log(`Retrying in ${waitTime / 60000} minutes...`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
return fetchSpaceEvents(retryCount + 1);
} else {
throw new Error("Max retries reached");
}
}
};
// Database update logic
const updateDatabase = async () => {
console.log("UPDATED THE DATABASE AT", new Date());
try {
const spaceEvents = await fetchSpaceEvents();
if (spaceEvents) {
const client = await getClient();
for (const event of spaceEvents) {
const query = { id: event.id };
const update = { $set: event };
const options = { upsert: true };
event.interested = event.interested ?? 0;
event.comments = event.comments ?? [];
await client
.db()
.collection<SpaceEvent>("SpaceEvents")
.updateOne(query, update, options);
}
}
} catch (error) {
console.error("Error updating database with space events:", error);
}
};
setInterval(updateDatabase, 1200000); // 20 minutes
我观察数据库更新日志的频率超过了 20 分钟的间隔。例如,日志指示更新时间为 11:47:04,然后是 11:49:41、11:49:53 等,这比预期间隔短得多。
我在 Firebase 上运行它,并使用 firebase emulators:start --only 函数进行本地测试。我不确定为什么该功能被如此频繁地触发。这是 Firebase 函数或模拟器的已知问题,还是我的代码中是否有某些内容导致此行为?
任何有关如何解决此问题的见解或建议将不胜感激。
// Import Firebase functions and admin modules
import * as functions from "firebase-functions";
import admin from "firebase-admin";
import { updateDatabase } from "../routes/spaceDevsRouter";
// Initialize Firebase Admin SDK
admin.initializeApp();
// Scheduled Cloud Function to update database every 20 minutes
export const scheduledSpaceEventUpdate = functions.pubsub
.schedule("every 20 minutes")
.onRun(async (context) => {
console.log("Scheduled update of space events started");
try {
await updateDatabase();
console.log("Scheduled update of space events completed successfully");
} catch (error) {
console.error("Error during scheduled update of space events:", error);
}
});
谢谢你