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
Size: 20
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
Thunk-based task scheduler that executes synchrounous and/or asynchronous tasks under concurrency control.
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.
t thunkWorkers = require('thunk-workers')
Create a workshop that limits the number of concurrent tasks being executed.
count
: {Number} Maximum number of task threads being executed concurrently. Default to 1
.t workshop = thunkWorkers(5)
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.
task
: {Function} Support sync task or async task, task must be a function or a generator function. Async task should be thunkable function, or return a thunkable value, such as thunk function, promise, generator function, generator object.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)