Skip to content

Instantly share code, notes, and snippets.

@sclark39
Created September 25, 2017 14:31
Show Gist options
  • Save sclark39/1f9297d6261ac8238fdf380132580541 to your computer and use it in GitHub Desktop.
Save sclark39/1f9297d6261ac8238fdf380132580541 to your computer and use it in GitHub Desktop.
This scheduler allows you to run multiple co "threads" that can yield and do async actions without being interrupted until explicitly declared.
var co = require('co')
var scheduler =
{
queue : []
}
// Requests control from scheduler
scheduler.promote = function()
{
if ( scheduler.asleep )
{
scheduler.asleep = false
scheduler.resume() // wake up the scheduler
}
return new Promise( resolve => scheduler.queue.push( resolve ) )
}
// Releases control of scheduler
scheduler.surrender = function()
{
scheduler.resume()
}
// Helper function to ensure the co "thread" requests control at the start,
// and releases when its done
scheduler.co = function( gen )
{
co( function*()
{
yield scheduler.promote()
yield gen()
scheduler.surrender()
} )
}
// Sleeps a co "thread", without giving up control
scheduler.sleep(t) = function{
return new Promise( resolve => setTimeout( resolve, t * 1000 ) )
}
// Sleeps a co "thread", allowing others to take control while it sleeps
scheduler.deepsleep = function*(t)
{
scheduler.surrender() // Release control in preperation
yield scheduler.sleep(t) // Go to sleep
yield scheduler.promote() // Awake again, request control!
}
// Auto-start the scheduler thread
co ( function*()
{
while ( true )
{
var next = scheduler.queue.shift()
if ( typeof next != 'undefined' )
next()
else
scheduler.asleep = true
yield new Promise( resolve => scheduler.resume = resolve )
}
} )
module.exports = scheduler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment