Skip to content

Instantly share code, notes, and snippets.

@luciyer
Last active November 17, 2020 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciyer/566b5244ed1d37cdc1176c1e22bc27a4 to your computer and use it in GitHub Desktop.
Save luciyer/566b5244ed1d37cdc1176c1e22bc27a4 to your computer and use it in GitHub Desktop.
bull.js job processing with socket.io
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
<h1>Socketzzz</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.1/socket.io.js"
integrity="sha512-vGcPDqyonHb0c11UofnOKdSAt5zYRpKI4ow+v6hat4i96b7nHSn8PQyk0sT5L9RECyksp+SztCPP6bqeeGaRKg=="
crossorigin="anonymous">
</script>
<script type="text/javascript">
const socket = io("http://localhost:8080")
socket.on("connect", () => {
console.log("Connected to socket.")
})
socket.on("message", (data) => {
console.log(data);
})
</script>
</body>
</html>
/* src/queue.js */
require("dotenv").config()
const Queue = require("bull")
const jobs = require("./jobs")
const deployQueue = new Queue("metadata_deploy", process.env.REDIS_URL)
deployQueue.process((job) => {
const { message } = job.data
return jobs.test({ message: message })
})
module.exports = {
deployQueue: deployQueue
}
/* server.js */
require("dotenv").config()
const express = require("express"),
http = require("http"),
socket = require("socket.io");
const { queue } = require("./src")
const app = express()
const server = http.createServer(app)
const io = socket(server)
app.use(express.json())
app.get("/test", async (req, res) => {
const deployInfo = { message: "Doin' something that takes 5 seconds." }
try {
const result = queue.deployQueue.add(deployInfo);
res.status(200).json({ message: "Job queued." })
} catch (error) {
res.status(500).json(error)
}
})
io.on("connection", (socket) => {
console.log("Client connected to Socket!")
queue.deployQueue.on("completed", (job, result) => {
console.log(`Job with id ${job.id} has been completed.`);
socket.emit("message", "Completed job!")
})
socket.on("disconnect", () => {
console.log("Client disconnected from Socket!")
})
})
app.get("/", function(req, res, next) {
res.sendFile(__dirname + "/index.html");
});
server.listen(process.env.PORT)
/* src/jobs/test.js */
module.exports = (data) => {
// Wait 5 seconds, then print the message.
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(data.message)
resolve()
}, 5000)
})
}
@luciyer
Copy link
Author

luciyer commented Nov 17, 2020

For long-running jobs, instead of using a poller I'd like to have the server notify the client over a socket. This is a POC, but needs to be extended to not emit globally, but only to the session which initiated the job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment