问题描述
我的网站上有一个流行度计数器我使用的是sails框架和node.js,我想使用cron库安排时间,所以当流行度在预定时间(例如一周)后> 15时,它会改变存档从假到真:
这是人气计数器:
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);
}
}
我的问题是如何用 javascript 编写代码?下面我粗略地猜了一下我会写什么:
var cron = require('node-cron');
x = popularity
if x < 15:
return cron.schedule('* * * * *',() => { // secs,mins,hours,DOM,month,DOW
change archived from false - true
});
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}`,'_blank');
} catch (error) {
console.log(error);
解决方法
Cron-job 肯定会起作用,但是如果 - 例如:任何东西的流行度在星期二超过 15,并且您愿意在每个星期五运行(cron job)它。在这种情况下,您将存档推迟到本周晚些时候设置,而应该在周二超过 15 点时完成。
因此,当您在代码中设置流行度时,请检查它是否超过阈值。如果它只是将 archived
设置为 true
。您可能不需要为此使用 cron 作业。
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);