I have a popularity counter in my website I am using sails framework and node.js, I want to schedule a time using the cron library so when popularity is > 15 after a scheduled time (a week for example) it changes the archived from false to true:
Here is the popularity counter:
const handlePopularityCount = async (event) => {
const bookmarkId = event.target.getAttribute('data-id') || '';
if (bookmarkId.length) {
try {
const bookmark = await get(`${URIS.BOOKMARKS}${bookmarkId}`);
const currentPopularity = bookmark.data.popularity || 0;
await patch(`${URIS.BOOKMARKS}${bookmarkId}`, {
popularity: currentPopularity + 1,
});
window.open(bookmark.data.url, '_blank');
} catch (error) {
console.log(error);
}
}
My issue is how would I write the code in javascript? Below I did a rough guess of what I would write:
var cron = require('node-cron');
x = popularity
if x < 15:
return cron.schedule('* * * * *' , () => { // secs, mins, hours, DOM, month, DOW
change archived from false - true
});
The popularity is getting counted by how many times the link is clicked in the frontend of the project:
const handlePopularityCount = async (event) => {
const bookmarkId = event.target.getAttribute('data-id',) || '',;
if (bookmarkId.length) {
try {
const bookmark = await get(`${URIS.BOOKMARKS}${bookmarkId}`);
const currentPopularity = bookmark.data.popularity || 0;
await patch(`${URIS.BOOKMARKS}${bookmarkId}`, {
popularity: currentPopularity + 1,
});
window.open(bookmark.data.url, '_blank');
} catch (error) {
console.log(error);
Cron-job will definitely work, but what if - for example: popularity for anything has crossed 15 on Tuesday and you are willing to run(cron job) it on every Friday. In this case, you are delaying the archive to set later in the week instead it should be done on Tuesday when it crosses the mark 15.
So, when you are setting the popularity in the code, check if it crosses the threshold. If it does just set the archived
to true
. You might not need to use cron job for this.
const handlePopularityCount = async (event) => {
const bookmarkId = event.target.getAttribute('data-id',) || '',;
if (bookmarkId.length) {
try {
const bookmark = await get(`${URIS.BOOKMARKS}${bookmarkId}`);
const currentPopularity = bookmark.data.popularity || 0;
if (currentPopularity > 15) {
//set the archived state
}
await patch(`${URIS.BOOKMARKS}${bookmarkId}`, {
popularity: currentPopularity + 1,
});
window.open(bookmark.data.url, '_blank');
} catch (error) {
console.log(error);