javascript - 使用节点 CRON 作业调用自己的请求
问题描述
我有以下片段:
const express = require('express')
const app = express()
const cronJob = require('cron').CronJob
app.get('/test', (req, res) => {
// Do something here
}
new cronJob('* * * * * *', () => {
// Call localhost:3000/test here
}, null, true, 'Asia/Manila')
app.listen(3000, () => console.log('Successfully listened to app 3000'))
如果在浏览器上调用它,通常在节点上运行 localhost:3000/test 对吗?一旦节点应用程序启动,我想让 CRON 运行它而不在浏览器上键入它。如果可能的话,无论主机名如何,无论它是否是 localhost,CRON 都应该在不输入浏览器的情况下发出请求。这可以做到吗?
解决方案
我阅读了上面关于问题本身的评论,并决定添加我的想法,即使您似乎有解决方案。
在我看来,调用“方法”本身而不是点击“http”来获得所需的响应会更干净。
您有 2 个选项:
- 通过请求调用点击“domain.com/test”端点。
- 只需调用与上述 url 相同的方法即可。通过这种方式,您将“节省”需要“设置”到具有响应和请求标头的快速应用程序的新请求的开销。(下面的例子)
假设这是您的代码:
const handleTestData = () => return 'something';
app.get('/test', (req, res) => {
const result = handleTestData();
res.send(result);
}
new cronJob('* * * * * *', () => {
// instead of calling http and getting the response
// and adding overhead, just call the function
const result = handleTestData();
// do what you need with the result
}, null, true, 'Asia/Manila')
推荐阅读
- python-3.x - 使用 OCR(光学字符识别)读取扫描的 PDF (JPEG) 的内容
- android - Android Firebase 查询按姓名或电子邮件或电话号码搜索用户
- amazon-web-services - 如何使用 eksctl 获取 EKS 节点组的卷大小?
- qt - 使用 JSON 的具有多行和多列的 Qt Quick QML GridLayout
- sql - SQL PDO “@P1”附近的语法错误
- django - Django on migrate 说关系不存在
- python - 在 Python 中添加多个字典列表的内容
- reactjs - React-Table 与 React-components 混合
- c - 我怎样才能得到一个makefile来管理条件编译?
- airflow-scheduler - Apache Airflow - 使用 RBAC 的身份验证问题