forked from crazyzzcc/jd_scripts-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (88 loc) · 3.02 KB
/
index.js
File metadata and controls
93 lines (88 loc) · 3.02 KB
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
87
88
89
90
91
92
93
//'use strict';
const { execFile } = require( 'child_process' );
const { readFileSync, existsSync } = require( 'fs' )
exports.main_handler = async ( event, context, callback ) => {
var eventObj;
eventObj = JSON.parse( event ).payload
console.log( `开始执行: 参数为:${ eventObj }` )
let scripts = [];
scripts = loadScripts( eventObj );
const tasks = [];
const count = 5;
for ( let i = 0; i < scripts.length; i++ ) {
const script = scripts[i];
if ( i > count ) {
await tasks[i - count];
delete tasks[i - count];
}
console.log( `run script:${ script }` )
const name = './' + script + '.js'
tasks[i] = new Promise( ( resolve ) => {
const child = execFile( process.execPath, [name] )
child.stdout.on( 'data', function ( data ) {
console.log( data )
} )
child.stderr.on( 'data', function ( data ) {
console.error( data )
} )
child.on( 'close', function ( code ) {
console.log( `${ script } finished` )
delete child
resolve()
} )
} )
}
await Promise.all( tasks )
callback( null, "执行完毕" )
}
function loadScripts ( msg, includeAll ) {
let now_hour = ( new Date().getUTCHours() + 8 ) % 24
console.log( 'hourly config触发,当前:', now_hour )
if ( msg ) {
const hour = Number( msg )
if ( !isNaN( hour ) && hour >= 0 && hour <= 23 ) {
now_hour = hour
console.log( 'hourly config触发,自定义触发小时:', now_hour )
}
}
const scripts = [];
if ( msg == 'config' ) {
const config_file = __dirname + '/config.json'
if ( existsSync( config_file ) ) {
console.log( `${ config_file } 存在` )
} else {
console.error( `${ config_file } 不存在,结束` )
process.exit()
}
try {
config = JSON.parse( readFileSync( config_file ) )
} catch ( e ) {
console.error( `读取配置文件失败:${ e }` )
return []
}
for ( let script in config ) {
if ( includeAll ) {
scripts.push( script )
continue;
}
// console.debug(`script:${script}`)
const cron = config[script]
if ( typeof cron == 'number' ) {
// console.debug(`number param:${cron}`)
if ( now_hour % cron == 0 ) {
console.debug( `${ script }:数字参数触发` )
scripts.push( script )
}
} else {
// console.debug(`dict param:${cron}`)
if ( cron.includes && cron.includes( now_hour ) ) {
console.debug( `${ script }:列表参数触发` )
scripts.push( script )
}
}
}
} else {
scripts.push( msg )
}
return scripts;
}