javascript - 在预定时间调用 API
问题描述
我试图在预定时间运行 API 调用。我通过网站进行了研究,发现了这个来自 npmjs 的名为 node-schedule 的包。通过在需要的时间调用代码,这可以按预期工作。我遇到的问题是:
假设我有一个时间列表,例如:["10:00","11:00","13:00"]
一旦我启动服务器,它将在需要的时间执行。但是,如果我想动态更改时间列表怎么办?
正是我想要做的:
- 调用 API 并从数据库中获取时间
- 为这些时间中的每一个设置 cron-schedule。
- 动态添加新时间到数据库
我想要的:将这个新添加的时间动态添加到cron-schedule
index.js
const express = require('express');
const schedule = require('node-schedule');
const app = express();
const port = 5000;
var date = new Date(2019, 5, 04, 14, 05, 20);// API call here
var j = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
app.get('/test', (req, res) => {
var date = new Date(2019, 5, 04, 14, 11, 0); // Will call API here
var q = schedule.scheduleJob(date, function(){
console.log('Hurray!!');
});
res.send('hello there');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
上面写的代码是我所拥有的,而且非常混乱。我在那里传达的是,在运行index.js
文件 API 时会调用并cron-schedule
执行。现在,如果有一些新值添加到数据库中,我想重新运行它。
重新运行index.js
是我的另一个选择,但我认为这不是正确的做法。我想到的下一个选项是调用/test
上面提到的另一个端点,它最终会再次运行 cron。
请让我知道一些建议或某种解决方案,以便我纠正我的错误。
解决方案
使用此代码,我认为您可以做您想做的事情,尽管您必须根据定义将执行任务的功能或是否需要指定以其他方式执行它们的时间(设置例如,一周中的特定日子)。
var times = [];
var tasks = [];
function addTask(time, fn) {
var timeArr = time.split(':');
var cronString = timeArr[1] + ' ' + timeArr[0] + ' * * *';
// according to https://github.com/node-schedule/node-schedule#cron-style-scheduling
var newTask = schedule.scheduleJob(cronString, fn);
// check if there was a task defined for this time and overwrite it
// this code would not allow inserting two tasks that are executed at the same time
var idx = times.indexOf(time);
if (idx > -1) tasks[idx] = newTask;
else {
times.push(time);
tasks.push(newTask);
}
}
function cancelTask(time) {
// https://github.com/node-schedule/node-schedule#jobcancelreschedule
var idx = times.indexOf(time);
if (idx > -1) {
tasks[idx].cancel();
tasks.splice(idx, 1);
times.splice(idx, 1);
}
}
function init(tasks) {
for (var i in tasks){
addTask(i, tasks[i]);
}
}
init({
"10:00": function(){ console.log("It's 10:00"); },
"11:00": function(){ console.log("It's 11:00"); },
"13:00": function(){ console.log("It's 13:00"); }
});
app.post('/addTask', (req, res) => {
if (!req.body.time.match(/^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$/)) {
// regex from https://stackoverflow.com/a/7536768/8296184
return res.status(400).json({'success': false, 'code': 'ERR_TIME'});
}
function fn() {
// I suppose you will not use this feature just to do console.logs
// and not sure how you plan to do the logic to create new tasks
console.log("It's " + req.body.time);
}
addTask(req.body.time, fn);
res.status(200).json({'success': true});
});
推荐阅读
- azure - 使用 Azure Devops Pipeline 将标签(带空格)传递给 ARM 模板
- python - 用 Ratio Proportion 填充 NAN 值
- java - PL/SQL 游标循环获取到 java
- ios - 带有 ForEach 删除动画的 SwiftUI 自定义列表不起作用
- ios - 如何获取 UITableViewHeaderFooter 的框架?
- android - 如何在 Android 库导入期间包含顶级构建文件?
- jakarta-ee - 所有 Jakarta EE 规范的摘要
- javascript - Vue.js - v-for 不渲染 api 调用响应数据
- python - 如果数据库中已经存在,如何在 django 中的 views.py 文件中添加条件以不创建相同的数据对象?
- docker - 如何在 Jenkins 从节点上运行 Dockerfile 代理?