About
- Node.js object wrapper for setInterval.
- It will help you remember about routine context.
- No external dependencies.
Installation
Requires Node.js v4.8.7
$ npm install strong-daemon
Examples
- Ordinary function:
const StrongDaemon = ; var daemon = 102 null { console } ; daemonstart; // Will print 'tick' 'tock' every ~102 ms /* (!) Note that multiple 'start' call without previous 'stop' will throw error */daemonstart; // First call made after ~102msdaemonstartfalse;// First call made after ~102msdaemonstarttrue; // First call made immediately; daemonstart;daemon; // truedaemon;daemon; // falsedaemonstart;
- Equivalent of above example
var daemon = 102 null consolelog 'tick' 'tock';
- Function that requires a caller context, because of
this
usage:
const worker = data: {} { thisdata = sourcedata; } var daemon = 102 worker /* So `this` will be handled properly on `updateData` call */ workerupdateData data_source; daemonstart;
- Example error scenario:
const worker = data: {} source: ... { thisdata = thissourcedata } var daemon = 101 null /* `this.source` will be undefined while daemon will call `updateData` */ workerupdateData; /* Error - `this.source` is undefined */daemonstart;
Mocking for test purposes:
/* your-lib.js */const getInstance = ; // :(const non_mockable_daemon = ...args; // :)const mockable_daemon = ;
/* test-your-lib.js */const D = ; D { return your_mock; }
Alternative way:
/* your-lib.js */const StrongDaemon getClass = ; const non_mockable_daemon = ...args const MockableStrongDaemon = ;const mockable_daemon = ...args;
/* test-your-lib.js */const D = ; D { return YourMock; }
Documentation
StrongDaemon
class -
constructor( interval_time, caller, task, task_args=[] )
Arguments:
interval
integer number - interval time of task call in milliseconds. Note this is not guarntee to call task every interval, it works exactly the same assetInterval(..).unref()
caller
object | null -task's
caller context (in case if task will use 'this' keyword)task
function - task that will be called everyinterval
[task_args]
Array - list of arguments task will be called with.
-
start( immediate_call )
Start daemon.Arguments:
immediate_call
- boolean, is task should be called immediately after start call. Default false.
-
stop()
Stop daemon (can be resterted by callingstart
). -
isRunning()
Returns:
- boolean, is daemon running
-
interval
getter for providedinterval_time
-
caller
getter for providedcaller
-
task
getter for providedtask
-
args
getter for providedargs
([] returned if not provided])
getInstance
function Provided for mocking purposes.
- Arguments: @see class
StrongDaemon
constructor - Returns: instance of StrongDaemon.
getClass
function Provided for mocking purposes.
- Arguments: no
- Returns: StrongDaemon class.