是否可以从代码中周期性地调用路由? 例如,我希望在每小时之后调用以下api
setInterval(function(){
app.post('/api/update_notices', (req, res) => {
res.send('notices updated!\n');
});
}, 10000);
您可以提取要定期执行的任务,并设置cron作业。
cron是一种基于时间的作业调度器,它使应用程序能够调度作业在某个日期或时间自动运行。
您可以签出库node-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
});
在crontab.guru上了解有关cron表达式的更多信息。
我认为最简单的解决方法就是把路由放到单独的函数中,直接调用它。
const express = import('express')
const app = express()
function updateNotices() {
// TODO
}
app.use('/api/update_notices' (req, res, next) => {
updateNotices()
res.end()
})
setInterval(() => {
updateNotices()
}, 10000)
使用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