Good Code
The good version makes startup explicit and returns a handle that can stop the background job.
Lesson 05
Avoid starting timers, connections, or jobs when a module is merely imported.
type CleanupJob = {
stop: () => void;
};
export function startCleanupJob(runCleanup: () => Promise<void>): CleanupJob {
const interval = setInterval(() => {
runCleanup().catch((error) => {
console.error({ error }, "Cleanup job failed");
});
}, 60_000);
return {
stop: () => clearInterval(interval),
};
}import { deleteExpiredSessions } from "../sessions";
setInterval(() => {
deleteExpiredSessions();
}, 60_000);
export function cleanupNow() {
return deleteExpiredSessions();
}The good version makes startup explicit and returns a handle that can stop the background job.
The bad version starts a timer at import time, so tests or scripts that only need cleanupNow also start an ongoing background loop.