-
Notifications
You must be signed in to change notification settings - Fork 0
/
JobManager.js
90 lines (84 loc) · 2.62 KB
/
JobManager.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
87
88
89
90
if (Meteor.isServer) {
JobManager = {};
let jobInfoMap = {};
JobManager.init = function(config) {
let maxJobCount = 5;
Meteor.setInterval(() => {
let runningJobs = _BackgroundJob.find({ status: constant['STATUS_STARTED'] }).fetch();
let runningJobsCount = runningJobs.length;
console.log('Running Jobs Count: ', runningJobsCount);
for (let i = runningJobsCount; i < maxJobCount; i++) {
pickJob();
}
}, 5000);
};
JobManager.register = function(name, jobFunction, customJobCompletedPoint) {
jobInfoMap[name] = {
jobFunction: jobFunction,
customJobCompletedPoint: customJobCompletedPoint || false
};
};
JobManager.run = function(obj) {
_BackgroundJob.insert({
type: obj.type,
priority: obj.priority,
status: constant['STATUS_NOT_STARTED'],
created: new Date(),
arguments: obj.arguments
});
};
JobManager.markJobFinished = function(jobId) {
_BackgroundJob.update({
_id: jobId
}, {
$set: {
status: constant['STATUS_SUCCESS']
}
});
};
function pickJob() {
let job;
try {
job = _BackgroundJob.find({
status: constant['STATUS_NOT_STARTED']
}, {
sort: {
'created': 1
},
limit: 1
}).fetch()[0];
if (job) {
console.log('created job: ', job._id);
_BackgroundJob.update({
_id: job._id
}, {
$set: {
'status': constant['STATUS_STARTED']
}
});
var func = jobInfoMap[job.type].jobFunction;
var _arguments = job.arguments;
_arguments.push(job._id);
func.apply(null, _arguments);
if (!jobInfoMap[job.type].customJobCompletedPoint) {
_BackgroundJob.update({
_id: job._id
}, {
$set: {
status: constant['STATUS_SUCCESS']
}
});
}
}
} catch (err) {
console.error(err);
_BackgroundJob.update({
_id: job._id
}, {
$set: {
status: constant['STATUS_FAILURE']
}
});
}
}
}