forked from heroku-examples/node-workers-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (49 loc) · 1.96 KB
/
server.js
File metadata and controls
60 lines (49 loc) · 1.96 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
let express = require('express');
let Queue = require('bull');
// Serve on PORT on Heroku and on localhost:5000 locally
let PORT = process.env.PORT || '5000';
// Connect to a local redis intance locally, and the Heroku-provided URL in production
let REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
let app = express();
// Create / Connect to a named work queue
let workQueue = new Queue('work', REDIS_URL);
// Serve the two static assets
app.get('/', (req, res) => res.sendFile('index.html', { root: __dirname }));
app.get('/client.js', (req, res) => res.sendFile('client.js', { root: __dirname }));
// Kick off a new job by adding it to the work queue
app.post('/job', async (req, res) => {
// This would be where you could pass arguments to the job
// Ex: workQueue.add({ url: 'https://www.heroku.com' })
// Docs: https://github.com/OptimalBits/bull/blob/develop/REFERENCE.md#queueadd
let job = await workQueue.add();
res.json({ id: job.id });
});
// Allows the client to query the state of a background job
app.get('/job/:id', async (req, res) => {
let id = req.params.id;
let job = await workQueue.getJob(id);
if (job === null) {
res.status(404).end();
} else {
let state = await job.getState();
let progress = job._progress;
let reason = job.failedReason;
res.json({ id, state, progress, reason });
}
});
// You can listen to global events to get notified when jobs are processed
workQueue.on('global:completed', (jobId, result) => {
console.log(`Job ${jobId} completed`);
});
// Message cleaning
workQueue.on('cleaned', function(jobs, type) {
console.log('Cleaned %s %s jobs', jobs.length, type);
});
// Clear queue every minute of processed and failed jobs.
setInterval(function() {
// Cleans all jobs that completed over 10 seconds ago,
// and cleans all jobs that failed over 2 minutes ago.
workQueue.clean(10000);
workQueue.clean(120000, 'failed');
}, 60000);
app.listen(PORT, () => console.log("Server started!"));