thunks/thunk-workers

Name: thunk-workers

Owner: thunks

Description: Thunk-based task scheduler that executes synchrounous and/or asynchronous tasks under concurrency control.

Created: 2015-09-09 06:14:24.0

Updated: 2017-03-14 14:32:52.0

Pushed: 2017-06-04 10:16:43.0

Homepage:

Size: 20

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

thunk-workers

Thunk-based task scheduler that executes synchrounous and/or asynchronous tasks under concurrency control.

NPM version Build Status Downloads

thunks
Demo
t thunk = require('thunks')()
t thunkWorkers = require('thunk-workers')
t workshop = thunkWorkers(2)

(let i = 1; i <= 10; i++) addWork(i)

tion addWork (id) {
rkshop(function () {
console.log('Task ' + id + ' start:')

let timer = setInterval(function () {
  process.stdout.write(String(id))
}, 50)

let time = 200 + Math.floor(1000 * Math.random())
if (id === 10) time = 10

return thunk.delay(time)(function () {
  clearInterval(timer)
  return time
})
(function (error, res) {
console.log(error || ('\nTask ' + id + ' finished, ' + res + ' ms.'))



esult:
ask 1 start:
ask 2 start:
21212121212121212
ask 2 finished, 510 ms.
ask 3 start:
3131313131313131
ask 1 finished, 981 ms.
ask 4 start:
43434343434343434343434343
ask 3 finished, 1199 ms.
ask 5 start:
5454545454
ask 4 finished, 1031 ms.
ask 6 start:
65656565656565656
ask 6 finished, 485 ms.
ask 7 start:
757575757
ask 5 finished, 1072 ms.
ask 8 start:
8787878787
ask 8 finished, 317 ms.
ask 9 start:
979797979
ask 7 finished, 886 ms.
ask 10 start:
ask 9 finished, 284 ms.
ask 10 finished, 10 ms.
API
t thunkWorkers = require('thunk-workers')
thunkWorkers([count])

Create a workshop that limits the number of concurrent tasks being executed.

t workshop = thunkWorkers(5)
workshop(task)

Return a thunk function that executes a specific task. Tasks are queued by the time the returned thunk function is executed. Once the number of concurrent tasks is within workshop's limitation, a task is polled from the queue and executed.

upport thunk function
t job = workshop(function (callback) {
tTimeout(function () {
callback(null, 'Async task')
 100)


function (err, res) {
nsole.log(err, res)


upport Promise
shop(function () {
turn Promise.resolve('promise')
unction (err, res) {
nsole.log(err, res)


upport Generator function
shop(function * () {
eld thunk.delay(100)
nsole.log('Generator task')
unction (err, res) {
nsole.log(err, res)


pport async/await function
shop(async function () {
ait Promise.resolve()
nsole.log('async/await task')
unction (err, res) {
nsole.log(err, res)


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.