【问题标题】:how can i update the data dynamically after some time using nodejs?使用nodejs一段时间后如何动态更新数据?
【发布时间】:2020-01-12 22:55:38
【问题描述】:

假设当我点击 GET 请求时响应来自服务器:

API 响应

[
{
  id: 1
  status: "Pending",
  startedAt: "10:30",
  endsAt: "12:30"
},
 {
  id: 2
  status: "Pending",
  startedAt: "11:30",
  endsAt: "1:30"
 },
....
]

现在我想在每 1 小时后将此状态字段更改为 Started 然后 Finished

我如何使用 node.js 来做到这一点,以及这样做的正确实现应该是什么。

【问题讨论】:

  • 如果不断添加新条目,您可以在后端每小时运行一次 Cron 作业。
  • 如果您想更改数据库中的这些数据,也许您应该使用 cron Job 库,例如 npmjs.com/package/cron
  • setInterval怎么样?

标签: node.js mongodb api express


【解决方案1】:

您可以使用 cron job

步骤 1) npm i crontab --save
第二步)npm i node-cron --save

现在在您的 index.js 或在您的 main 节点的 js 文件中。编写以下命令。

const cron = require('node-cron');
const crontab = require('node-crontab');

crontab.scheduleJob("0 * * * * " , function(){
     //do something cool    
},{
    schedule: true,
    timezone: "Asia/kolkata"
});

上述函数将每 1 小时运行一次,您可以在其中编写代码。

欲了解更多信息,请通过official Document

【讨论】:

    【解决方案2】:

    您可以简单地使用setInterval 在特定时间间隔后执行操作。

    var yourData = [
      {
        id: 1
        status: "Pending",
        startedAt: "10:30",
        endsAt: "12:30"
      },
       {
        id: 2
        status: "Pending",
        startedAt: "11:30",
        endsAt: "1:30"
       },
      ....
      ]
    async function updateData(){
      //Call your API and update the data
      yourData = await yourAPICall()
    }
    
    setInterval(updateData, 60 * 60 * 1000)
    

    【讨论】:

    • 这个函数会在每个特定时间后调用还是只运行一次。
    • @Ravi 这将每 1 小时调用一次 updateData = 3600000 毫秒。
    • @Ravi 你可以通过setInterval(() => console.log(new Date()), 5000)查看
    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多