我有一个node.js脚本,用于创建与加密交易网站(bitmex)的websocket连接。它流传输价格数据。
在一两个小时后,由于某种原因,流变坏了,价格(如果完全流化了)是不准确的。
目前,我每小时都会手动重新启动它,但我需要自动完成。我该怎么办?
这是脚本的代码:
var WebSocket = require('ws');
var ws = new WebSocket("wss://www.bitmex.com/realtime");
var couchbase = require('couchbase')
var cluster = new couchbase.Cluster('couchbase://localhost/');
cluster.authenticate('xxxxxx', 'xxxxxxx');
var bucket = cluster.openBucket('test');
var N1qlQuery = couchbase.N1qlQuery;
let num_msg = 0;
ws.onopen = function(){
ws.send(JSON.stringify({"op": "subscribe", "args": [
"trade:XBTUSD",
"trade:LTCZ18"]
}))
};
ws.onmessage = function(msg){
var response = JSON.parse(msg.data);
num_msg++
if(num_msg > 50) {
var coin = response['data'][0]['symbol'];
var price = response['data'][0]['price'];
//console.log(coin + ":" + price + "\n");
bucket.manager().createPrimaryIndex(
function(){
bucket.upsert( coin,
{
'price': price
},
function (err, result){
});
});
}
};
编辑:我错过了提及我当前使用Windows 7系统的情况(尽管我确实需要迁移到Ubuntu或类似系统)。
编辑2:我的代码的最终版本:)
const cron = require("node-cron");
var WebSocket = require('ws');
var couchbase = require('couchbase');
var dateTime = require('node-datetime');
let now = new Date();
minutes = now.getMinutes() + 1;
if(minutes + 30 > 59) {
minutes1 = minutes - 30;
} else {
minutes1 = minutes - 30;
}
if(minutes > minutes1) {
s_cron = minutes1 + "," + minutes + " * * * *";
} else {
s_cron = minutes + "," + minutes1 + " * * * *";
}
cron.schedule(s_cron, () => {
console.log("---------------------");
console.log("Running Cron Job");
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
console.log(formatted);
// create bitmex ws
var ws = new WebSocket("wss://www.bitmex.com/realtime");
// connect to couchbase
var cluster = new couchbase.Cluster('couchbase://localhost/');
cluster.authenticate('xxxxxxxx', 'xxxxxxxxxx');
var bucket = cluster.openBucket('test');
var N1qlQuery = couchbase.N1qlQuery;
let num_msg = 0;
ws.onopen = function(){
ws.send(JSON.stringify({"op": "subscribe", "args": [
"trade:XBTUSD",
"trade:LTCZ18"]
}))
};
ws.onmessage = function(msg){
var response = JSON.parse(msg.data);
num_msg++
if(num_msg > 50) {
var coin = response['data'][0]['symbol'];
var price = response['data'][0]['price'];
//console.log(coin + ":" + price + "\n");
bucket.manager().createPrimaryIndex(
function(){
bucket.upsert( coin,
{
'price': price
},
function (err, result){
//bucket.disconnect()
});
});
}
};
});
答案 0 :(得分:2)
尝试使用“ node-cron”:更多有关https://www.npmjs.com/package/node-cron的信息,希望如此。
答案 1 :(得分:1)
请考虑使用cron
每小时重新启动一次。您的crontab
条目如下:
0 * * * * <command to restart your app>
如果您不能或不想使用系统crontab
或同等系统(不确定在Windows上将使用什么系统),则可以使用pm2
。
pm2
:https://www.npmjs.com/package/pm2
有关如何使pm2
每小时重新启动,请参见https://github.com/Unitech/pm2/issues/1076或https://stackoverflow.com/a/38062307/436641。
另一种选择是node-cron
:https://www.npmjs.com/package/node-cron