首页 > 解决方案 > 使用节点 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 都应该在不输入浏览器的情况下发出请求。这可以做到吗?

标签: javascriptnode.jsexpress

解决方案


我阅读了上面关于问题本身的评论,并决定添加我的想法,即使您似乎有解决方案。

在我看来,调用“方法”本身而不是点击“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')

推荐阅读