这不需要是一个 Express 应用程序,而是一个在指定时间间隔触发的简单 Node.js 脚本。你要找的是Cron。
如果您想保留当前的 Express 应用程序,那么我建议保留其当前结构,但使用类似 node-schedule 的内容。所以在另一个文件中,你可以有类似的东西:
// my-job.js
const schedule = require('node-schedule')
module.exports = schedule.scheduleJob('42 * * * *', () => {
console.log('The answer to life, the universe, and everything!')
})
然后在您的主app.js 中,只需导入文件即可开始工作:
const express = require('express')
...
require('./my-job')
然后在/shutdown 这样的另一条路线上,你可以这样做:
const express = require('express')
const j = require('./my-job')
const router = express.Router()
router.get('/shutdown', () => {
j.cancel()
res.json({ message: 'Canceled.' })
})
这只是一个想法,以上没有经过测试。
但请记住,抓取网站是一个灰色区域。如果他们提供 API,请改用它。