【问题标题】:Self invoke an api route in express js在 express js 中自调用 api 路由
【发布时间】:2020-06-09 12:59:32
【问题描述】:

是否可以在代码中定期调用路由? 例如,我希望每隔一小时调用一次以下 api

setInterval(function(){
  app.post('/api/update_notices', (req, res) => {
    res.send('notices updated!\n');
  }); 
}, 10000);

【问题讨论】:

  • 如果您希望某段代码在某个时间段执行,请查看node-cron。您当前的方法需要设置像 superagent 这样的客户端并发出请求
  • 这段代码没有意义我的意思是你想给谁发回复?为什么?

标签: javascript node.js api express


【解决方案1】:

您可以提取要定期执行的任务并设置 cron 作业。

cron 是一个基于时间的作业调度程序,它使应用程序能够 安排作业在特定日期或时间自动运行。

您可以查看图书馆node-cron。这是一个代码sn-p供您参考:

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

// '0 * * * *' is a cron expressions which means the task will run at minute 0 every hour.
cron.schedule('0 * * * *', () => { 
  // perform the task
});

Crontab.guru 上了解有关 cron 表达式的更多信息。

【讨论】:

  • 是的,几分钟前遇到了这个……正在努力。 {欢迎来到 stackoverflow :) }
【解决方案2】:

我使用节点调度来实现这种功能。

node-schedule

我很困惑为什么你需要在这个间隔内从你的前端打一条路线。您只需要该功能在指定的时间间隔在服务器上运行,因此不需要路由。

简单示例:

const schedule = require('node-schedule');

schedule.scheduleJob( '*0***', yourFunction ) //runs every hour

【讨论】:

    【解决方案3】:

    我认为最简单的解决方案是将路由放入单独的函数中并直接调用。

    const express = import('express')
    const app = express()
    
    function updateNotices() {
      // TODO
    }
    
    app.use('/api/update_notices' (req, res, next) => {
      updateNotices()
      res.end()
    })
    
    setInterval(() => {
      updateNotices()
    }, 10000)
    

    【讨论】:

      【解决方案4】:

      使用cron 或其他允许定期操作的系统服务:

      将此行放入您的crontab(应每分钟执行一次):

      * * * * * curl http://your-site.example.org/api/update_notices
      

      您也可以编写执行此操作的外部程序:

      Bash 代码:

      #!/bin/bash
      
      # Executes curl every 10 secs
      while sleep 10
      do
          curl http://your-site.example.org/api/update_notices
      done
      

      【讨论】:

        猜你喜欢
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多