-
Notifications
You must be signed in to change notification settings - Fork 2
/
crawl-queue.js
89 lines (69 loc) · 2.16 KB
/
crawl-queue.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
var _ = require('underscore');
var CrawlQueue = function CrawlQueue(options) {
this.defaultOptions = {
baseInterval: 10000,
intervalMargin: 2500,
waitNewJobInterval: 1000
}
this.options = _.extend(this.defaultOptions, options);
this.queue = [];
this.isRunning = false;
this.crawlNextTimeout = false;
};
CrawlQueue.prototype.enqueue = function crawl(id, uri, crawlEngine, onDone) {
this.queue.push({
id: id,
uri: uri,
crawlEngine: crawlEngine,
onDone: onDone
});
console.log('Queued URI ' + uri + ', queue length: ' + this.getLength());
};
CrawlQueue.prototype.run = function run() {
this.isRunning = true;
var onDone = function onDone(result) {
var nextInterval = 0;
if (result === false) {
// No job executed, let's wait for a new one
nextInterval = this.options.waitNewJobInterval;
} else {
// A proper result
nextInterval = this.generateInterval();
}
console.log('Scheduling next job in ' + nextInterval);
this.scheduleNextCrawl(nextInterval, onDone);
}.bind(this);
this.crawlNext(onDone);
};
CrawlQueue.prototype.stop = function stop() {
this.isRunning = false;
clearTimeout(this.crawlNextTimeout);
this.crawlNextTimeout = false;
};
CrawlQueue.prototype.crawlNext = function crawlNext(onDone) {
if (this.getLength() > 0) {
var currentJob = this.queue.pop();
var crawlEngine = currentJob.crawlEngine;
console.log('Crawling ' + currentJob.uri);
crawlEngine.crawl(currentJob.uri, function (result) {
currentJob.onDone(result);
onDone(result);
});
} else {
onDone(false);
}
};
CrawlQueue.prototype.scheduleNextCrawl = function scheduleNextCrawl(interval, onDone) {
this.crawlNextTimeout = setTimeout(function () {
this.crawlNext(onDone.bind(this));
}.bind(this), interval);
}
CrawlQueue.prototype.getLength = function getLength() {
var result = this.queue.length;
return result;
};
CrawlQueue.prototype.generateInterval = function generateInterval() {
var result = this.options.baseInterval + (Math.random() * this.options.intervalMargin * 2 - this.options.intervalMargin);
return result;
}
module.exports = CrawlQueue;