Skip to content

Commit

Permalink
Merge pull request #2425 from airqo-platform/hotfix-schedule-sim-status
Browse files Browse the repository at this point in the history
scheduling daily SIM status checks
  • Loading branch information
Baalmart authored Nov 5, 2023
2 parents da59183 + db58dec commit 0517d92
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
58 changes: 58 additions & 0 deletions src/incentives/bin/cronJob.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const cron = require("node-cron");
const SimModel = require("@models/Sim");
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- bin/cronJob script`
);
const checkStatus = require("@utils/create-sim").checkStatus;
const secondsDelayBetweenRequests = 20000;
const internetDataBalanceThreshold = 5;

// Everyday at midnight
cron.schedule("0 0 * * *", async () => {
try {
const batchSize = 100; // Process 100 SIM cards at a time
let skip = 0;

const simCards = await SimModel("airqo").find({}).select("_id").lean();

while (true) {
const simBatch = simCards.slice(skip, skip + batchSize);

if (simBatch.length === 0) {
break;
}

await processSimCardsWithDelay(simBatch);

skip += batchSize;
}
} catch (error) {
logger.error(
`An error occurred in the cron job --- ${JSON.stringify(error)}`
);
}
});

async function processSimCardsWithDelay(simBatch) {
for (const sim of simBatch) {
const responseFromCheckStatus = await checkStatus({
query: { tenant: "airqo" },
params: { sim_id: sim._id },
});

// Check if data.balance is less than the declared threshold and log it
if (
responseFromCheckStatus.success &&
responseFromCheckStatus.data.balance < internetDataBalanceThreshold
) {
logger.info(
`SIM card ${sim._id} has a balance less than ${internetDataBalanceThreshold}`
);
}
await new Promise((resolve) =>
setTimeout(resolve, secondsDelayBetweenRequests)
);
}
}
35 changes: 35 additions & 0 deletions src/incentives/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/incentives/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"mongoose-unique-validator": "^2.0.3",
"morgan": "~1.9.0",
"mtn-momo": "^2.0.0",
"node-cron": "^3.0.2",
"node-fetch": "^2.6.1",
"node-schedule": "^2.1.1",
"nodemailer": "^6.9.4",
Expand Down

0 comments on commit 0517d92

Please sign in to comment.