Javascript 在expressjs中自调用api路由

Javascript 在expressjs中自调用api路由,javascript,node.js,api,express,Javascript,Node.js,Api,Express,是否可以从代码中定期调用路由? 例如,我希望在每小时后调用以下api setInterval(function(){ app.post('/api/update_notices', (req, res) => { res.send('notices updated!\n'); }); }, 10000); 我认为最简单的解决方案是将路由放入单独的函数中并直接调用它 const express=导入“express” const app=express 函数更新注释{ /

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

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

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

const express=导入“express” const app=express 函数更新注释{ //待办事项 } 应用程序。使用“/api/update_notices”请求,res,next=>{ 更新注释 res.end } setInterval=>{ 更新注释 }, 10000 使用cron或其他允许定期操作的系统服务:

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

* * * * * curl http://your-site.example.org/api/update_notices
您还可以编写执行以下操作的外部程序:

Bash代码:

!/bin/bash 每10秒执行一次curl 而睡眠10 做 卷曲http://your-site.example.org/api/update_notices 完成
您可以提取要定期执行的任务并设置cron作业

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

你可以去图书馆看看。以下是一段代码片段供您参考:

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
});

了解有关上的cron expression的详细信息。

我使用节点计划实现此类功能

我不明白为什么你需要在这个时间间隔内从你的前端到达一条路线。您只需要在服务器上以指定的时间间隔运行该函数,因此不需要路由

简单的例子:

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

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

如果希望在某个时间段执行某些代码,请检查节点cron。您当前的方法将需要设置一个像superagent这样的客户端并发出请求。这段代码毫无意义,我的意思是您想向谁发送响应?为什么?是的,几分钟前我遇到了这个。。正在努力。{欢迎使用stackoverflow:}