1.2.0 • Published 7 years ago

@sumanion/queue v1.2.0

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

Queue Manager

Fast, unopinionated, minimalist queue manager for Node.js

Installation

Using npm:

$ npm install @sumanion/queue --save

Using yarn:

$ yarn add @sumanion/queue

Usage

// Load the module.
const queue = require('@sumanion/queue')

// Create a queue manager with default options.
const q = queue.create()

// Or set custom options.
const q = queue.create({
  // Maximum number of concurrent active tasks.
  max: 1, // Accepted values: 1..Infinity
  // Queue manager will automatically start to run tasks.
  start: true // Accepted values: true or false
})

// Set the maximum number of concurrent active tasks.
q.max(1)

// Start the queue manager.
q.start()

// Stop the queue manager.
q.stop()

// Return the number of tasks in the queue.
q.size()

// Show the number of active tasks.
q.active()

// Remove all queued tasks.
q.clear()

// Add a new task to the queue.
q(next => {
  // The task contents.
  console.log(1)

  // IMPORTANT: When the task finishes it's job you should
  // always call the `next()` method to start the next task.
  next()
})

// Add another task to the queue.
q(next => {
  // The task contents.
  console.log(2)

  // NOTE: You can wait as long as you need before you call
  // the `next()` method.
  setTimeout(() => {
    // IMPORTANT: When the task finishes it's job you should
    // always call the `next()` method to start the next task.
    next()
  }, 1000)
})

// The queue manager will output:
// 1
// 2

Task Priorities

  • High Priority Tasks - are executed before all other tasks. If there are many high priority tasks they are executed in the order they were added to the queue manager.
q.high(next => {
  next()
})
  • Normal Priority Task - are executed after all high priority tasks. If there are many normal priority tasks they are executed in the order they were added to the queue manager.
q(next => {
  next()
})
  • Low Priority Tasks - are executed after all high priority and normal priority tasks. If there are many low priority tasks they are executed in the order they were added to the queue manager.
q.low(next => {
  next()
})

Important Notes

  • Queue manager will always keep the tasks in the order you added them.
  • You should always call the next() method manually when your tasks finish to do their jobs.

Possible Issues

  • next() method inside a task must be called exactly one time, because it decreases the number of currently active tasks by one and if you call it multiple times it will run the wrong number of concurrent tasks. Of course it will back to normal shortly, but you should be aware of this side effect.
  • If you will not call the next() method on a task when it finishes it's job, queue manager will not start another tasks, it will wait forever the previous task to finish.

License

MIT

1.2.0

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago