Last active
July 2, 2023 16:55
-
-
Save luizcalaca/a7f249b8a7a9a9c7de8ae6b1fd67496a to your computer and use it in GitHub Desktop.
Node.js + BullMQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Worker } = require('bullmq') | |
const redisConfiguration = { | |
connection: { | |
host: "localhost", | |
port: 6379, | |
username: "default", | |
password: "redispw" | |
} | |
} | |
function sendEmail(job) { | |
const { email, message } = job.data; | |
console.log(`Message ${message} was sent to ${email}.`) | |
} | |
const worker = new Worker('emailSchedule', sendEmail, { | |
redisConfiguration, | |
batches: { size: 10 }, | |
concurrency: 5, | |
}); | |
const shutdown = async () => { | |
await worker.close(); | |
process.exit(0); | |
}; | |
process.on("SIGINT", shutdown); | |
process.on("SIGTERM", shutdown); | |
worker.on('completed', job => { | |
console.info(`${job.id} has completed!`); | |
}); | |
worker.on('failed', (job, err) => { | |
console.error(`${job.id} has failed with ${err.message}`); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Queue } = require('bullmq') | |
const crypto = require('crypto'); | |
// Add your own configuration here | |
const redisConfiguration = { | |
connection: { | |
host: "localhost", | |
port: 6379, | |
username: "default", | |
password: "redispw" | |
} | |
} | |
const myQueue = new Queue('emailSchedule', { | |
redisConfiguration, | |
}); | |
async function emailSchedule(email, message, delay) { | |
await myQueue.add(crypto.randomUUID(), { email, message }, { | |
delay, | |
attempts: 3, | |
backoff: { | |
type: 'exponential', | |
delay: 1000, | |
}, | |
repeat: { | |
every: 3000, // Repeat job every 3 seconds but no more than 100 times | |
limit: 100, | |
}, | |
priority: 1, | |
removeOnComplete: { | |
age: 1000 * 60 * 60 * 24 * 30, // Remove job from completed list after 30 days | |
count: 10 //Mantém 10 jobs | |
}, | |
removeOnFail: 5000, // Remove job from failed list after 5 seconds | |
}); | |
} | |
emailSchedule("foo@bar.com", "Hello World!", 5000, 1); // The email will be available for consumption after 5 seconds. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to run?
Redis: docker run -d -p 6379:6379 --name my-redis -e REDIS_PASSWORD=redispw redis
npm i bullmq