-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (48 loc) · 1.3 KB
/
index.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
const schedule = require('node-schedule');
const ddns = require('./lib/ddns')
const { getIP } = require('./lib/util');
const DingRobot = require('./lib/dingding')
const robot = new DingRobot()
// 执行的任务
let lastIP = ''
const jobFun = async () => {
ip = await getIP().catch(e => {
return Promise.reject(`get publicip failed \n${e.toString()}`)
})
if (lastIP === ip) return ip
await ddns(ip)
.catch(e => {
return Promise.reject(`ddns failed: ${ip}\n ${e.toString()}`)
})
return ip
}
// 开始执行任务
const sleepTime = 5000
const job = schedule.scheduleJob(new Date().getTime() + sleepTime, jobFun)
job.on('success', ip => {
if (lastIP === ip) {
console.log('ip not change')
return
}
lastIP = ip
robot.sendText(`ddns success: ${ip}`)
})
job.on('error', msg => {
robot.sendText(`ddns failed: ${msg}`)
})
setTimeout(() => {
job.reschedule('*/10 * * * *')
}, sleepTime)
robot.sendText('ddns start')
/** 异常退出监控 */
const onExit = signal => {
return async () => {
await robot.sendText(`receive signal ${signal}, ddns stop`)
await schedule.gracefulShutdown()
process.exit(0)
}
}
const signals = ['SIGINT', 'SIGTERM']
signals.forEach(key => {
process.on(key, onExit(key))
})