Mastering Firebase Function Scheduling (Cron Job) ๐
Hello, fellow developers! If the idea of having your code automatically check and update your e-commerce store's stock interests you, you've landed in the right place. Today, we're diving deep into how you can harness Firebase cron jobs and schedulers for such tasks. Let's simplify this!
๐ The Power of Cron Jobs in Firebase
In the tech realm, a "cron job" refers to tasks that are scheduled to run at regular intervals without any manual intervention. Firebase brings this capability to the forefront via Cloud Functions. Imagine Firebase cron jobs as diligent assistants who never miss their scheduled checks.
For a basic understanding, here's a cron job that runs every 10 minutes:
exports.handleOptionEntry = onSchedule("every 10 minutes", async () => {
console.log("this runs every 10 minutes")
});
But how can this be applied to a real-world scenario?
๐ป E-commerce Scenario: Auto-Checking Order Status and Updating Stock
Imagine this: You run an online store selling various products. It's essential for you to keep an eye on orders to know which ones are delivered. Based on this, you want to update your store's stock. Here's how a Firebase scheduler can handle this:
exports.checkAndUpdateStock = onSchedule("every day 00:00", async () => {
const db = admin.firestore();
const ordersRef = db.collection("orders");
const productsRef = db.collection("products"); // 'products' is our collection of items in stock
try {
const snapshot = await ordersRef.get();
snapshot.docs.forEach(async (doc) => {
const order = doc.data();
if (order.status === "delivered") {
const product = await productsRef.doc(order.productID).get();
if (product.exists) {
const productData = product.data();
productsRef.doc(order.productID).update({ stock: productData.stock - order.quantity });
}
}
});
console.log("Stock updated based on delivered orders.");
} catch (error) {
console.error("Error updating stock:", error);
}
});
In this scheduler, every day, the system checks for orders marked as "delivered". For each delivered order, it then deducts the ordered quantity from the product stock.
๐งช (Optional) Manually Trigger Your Scheduler (Crown Job) for Testing Purposes:
If you're looking to test this function before deploying it to the cloud, Firebase offers a local emulator to help with this. First, ensure you've set up the Firebase functions emulator in your local environment. Once everything's in place, you can utilize the Firebase shell to manually trigger the function and see it in action. Simply launch the shell using firebase functions:shell
and then call your function with firebase > checkAndUpdateStock()
. This offers a handy way to debug and ensure everything works as expected before moving it live.
- Launch the Firebase shell:
firebase functions:shell
- Directly call your scheduled function:
firebase > checkAndUpdateStock()
That's it! Your cron job runs instantly, updating your stock based on delivered orders.
๐ Deployment of the Function
After confirming that your function works as intended locally, you can deploy it to Firebase. Deploy your function using the following command:
firebase deploy --only functions:checkAndUpdateStock
Replace checkAndUpdateStock
with the name of your specific function if it's different. Once deployed, your function will be operational in the cloud, and the scheduler will execute it as configured.
๐๐ป Embrace automation and enhance efficiency by setting up your Firebase scheduler. Happy coding!
Subscribe to my newsletter
Read articles from Asad Javed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Asad Javed
Asad Javed
I am a Javascript Developer, who loves to deliver technical content.