I have a route in my expressjs which calls some logic on an interval:
export const get = (req, res) => {
const { ids } = req.query;
let interval = setInterval(() => {
let id = ids.pop()
console.log("On id #:", id)
// do some stuff with the id
if (!ids.length) {
clearInterval(interval)
}
}, 1000)
interval.unref();
res.json();
};
So if you hit the route that calls this function, code runs every 1 second, and prints the console statement. This is all within an express server. If the process runs to completion, great. However, I notice that even if I ctrl c
out of the server's running process before the interval loop is done, the terminal continues printing the id every 1 second, until its done.
I thought the .unref()
method is supposed to prevent this, but it has no effect. I also tried this:
["exit", "uncaughtException", "SIGINT", "SIGTERM"]
.forEach(signal => {
process.on(signal, () => {
clearInterval(interval);
});
});
This also seems to have no effect. How can I make sure that any running intervals are stopped and cleared when I shut down my express server?
Maybe my issue has something to do with some convoluted logic for the setup and cleanup of my server. For reference:
import express from "express";
import { setRoutes } from "./routes";
let app = express();
const server = app.listen(8080, function () {
console.log(` Server is now running on port : ${8080}`);
});
app = setRoutes(app);
function stop() {
// Run some code to clean things up before server exits or restarts
server.on("close", function () {
console.log("⬇ Shutting down server");
process.exit();
});
server.close();
}
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
process.on("SIGQUIT", stop);
process.once("SIGUSR2", function () {
// Run some code to do a different kind of cleanup on nodemon restart:
process.kill(process.pid, "SIGUSR2");
});