【问题标题】:Trying to change a boolean value from false to true after a period of time in javascript在javascript中一段时间​​后尝试将布尔值从false更改为true
【发布时间】:2021-07-21 10:46:40
【问题描述】:

我在我的网站上有一个受欢迎程度计数器我正在使用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}`, {
      popularity: currentPopularity + 1,
    });
    window.open(bookmark.data.url, '_blank');
  } catch (error) {
    console.log(error);

【问题讨论】:

  • 你面临的问题是什么?
  • 问题已更新。我想知道我会写什么来完成这项工作
  • 人气更新背后的逻辑是什么?您必须更新还是由其他脚本计算?流程是什么?
  • 以上更新。在前端点击链接,当点击链接时,计数增加 1。所以我想运行一个计划作业,所以每周都会查看受欢迎程度,如果它低于 15,它会被存档。我有一个档案已经在工作了。

标签: javascript node.js sails.js archiving


【解决方案1】:

Cron-job 肯定会起作用,但是如果 - 例如:任何东西的流行度在周二超过 15,并且您愿意在每个星期五运行(cron 作业)它会怎样。在这种情况下,您将存档推迟到本周晚些时候设置,而不是应该在星期二超过 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);

【讨论】:

  • 非常感谢,我会试一试
  • 这个答案有帮助吗?
  • 您可以接受答案并点赞,我们都会因此得到奖励。谢谢!编码愉快!
猜你喜欢
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2020-02-07
相关资源
最近更新 更多