forked from chrisleekr/binance-trading-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-cronjob.js
86 lines (74 loc) · 2.41 KB
/
server-cronjob.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const { v4: uuidv4 } = require('uuid');
const config = require('config');
const { CronJob } = require('cron');
const { maskConfig } = require('./cronjob/trailingTradeHelper/util');
const { executeAlive, executeTrailingTradeIndicator } = require('./cronjob');
const fulfillWithTimeLimit = async (logger, timeLimit, task, failureValue) => {
let timeout;
const timeoutPromise = new Promise(resolve => {
timeout = setTimeout(() => {
logger.error(
{ tag: 'job-timeout' },
`Failed to run the job within ${timeLimit}ms.`
);
resolve(failureValue);
}, timeLimit);
});
const response = await Promise.race([task, timeoutPromise]);
/* istanbul ignore next */
if (timeout) {
// the code works without this but let's be safe and clean up the timeout.
clearTimeout(timeout);
}
return response;
};
const runCronjob = async serverLogger => {
const logger = serverLogger.child({ server: 'cronjob' });
logger.info(
{ config: maskConfig(config) },
`API ${config.get('mode')} trading started on`
);
const jobInstances = {};
// Execute jobs
[
{ jobName: 'alive', executeJob: executeAlive },
// { jobName: 'trailingTrade', executeJob: executeTrailingTrade },
{
jobName: 'trailingTradeIndicator',
executeJob: executeTrailingTradeIndicator
}
].forEach(job => {
const { jobName, executeJob } = job;
if (config.get(`jobs.${jobName}.enabled`)) {
jobInstances[jobName] = new CronJob(
config.get(`jobs.${jobName}.cronTime`),
async () => {
if (jobInstances[jobName].taskRunning) {
logger.info({ jobName }, 'Task is running, skip this tick');
return;
}
jobInstances[jobName].taskRunning = true;
const moduleLogger = logger.child({ job: jobName, uuid: uuidv4() });
// Make sure the job running within 20 seconds.
// If longer than 20 seconds, something went wrong.
await fulfillWithTimeLimit(
moduleLogger,
20000,
executeJob(moduleLogger),
null
);
jobInstances[jobName].taskRunning = false;
},
null,
false,
config.get('tz')
);
jobInstances[jobName].start();
logger.info(
{ cronTime: config.get(`jobs.${jobName}.cronTime`) },
`Job ${jobName} has been started.`
);
}
});
};
module.exports = { runCronjob };