als-time-manager
v4.2.0
Published
A versatile and efficient time management tool for scheduling tasks with ease.
Downloads
22
Maintainers
Readme
ALS Time Manager
ALS Time Manager is a powerful tool for time management and task scheduling. It provides flexible time control for nodejs.
Als Time Manager providing two main methods: $setTimeout
and $setInterval
, which works similar to regular js setTimeOut
and setInterval
respectively, but with extra options and extended support.
- Using only one setTimeout for all time tasks
- support for delays longer then 24.8 days (32bit limit)
- formatted input time option (like
'1:0:0:0'
for 1 day instead1000*60*60*24
) - margin for execution for improving performance
- managing time task (reset time, cancel) - include inside callback
- interval tasks with defined intervals (like run task after 100ms,200ms,500ms,100ms )
- access to all time tasks
Installation
Node.js
Using npm:
npm install als-time-manager
const TimeManager = require('als-time-manager');
const { $setTimeout, $setInterval, timeToMs } = TimeManager
timeToMs
TimeManager.timeToMs(timeValue)
is a static method which converts a string, number, or date object into its corresponding value in milliseconds.
This method used by TimeManager for time parameters.
Parameters:
timeValue
: A string, number, or date object representing time.- When provided as a string, it can be in the format
d:h:m:s.ms
, where:d
: days (optional)h
: hours (optional)m
: minutes (optional)s
: seconds (optional)ms
: milliseconds (optional)- Omitted values are considered as zero.
- If the time is represented as a number, it's interpreted as milliseconds.
- date object, will calculate time from now to the date
- When provided as a string, it can be in the format
if result value is negative, error will be thrown.
Examples:
Using a string:
timeToMs('1:1:1:1.100') // Returns 90061100
timeToMs('::1') // Returns 1000
timeToMs('2:3.50') // Returns 123500
Using a number:
timeToMs(5000) // Returns 5000
Using a date object:
const futureTime = new Date(2023, 11, 21, 5, 30, 0);
timeToMs(futureTime) // Returns the milliseconds difference between the provided date and the current date.
Errors:
The function will throw an error if the input value is invalid, negative, or represents a past time (in case of date objects).
Adding a Delayed Task ($setTimeout)
Syntax: $setTimeout(fn,delay,margin)
.
- Parameters
fn
- callback function to executefn(task)
- gets task as parameter
delay
- time in milliseconds or formatted string for timeToMS for task delaymargin
- time in milliseconds or formatted string for timeToMS for task margin
- returns
- instance of
Task
- instance of
Example:
const fn = (task) => {console.log('Task executed!')}
const task = TimeManager.$setTimeout(fn,3000,1100);
// or using timeToMs format
const task = TimeManager.$setTimeout(fn,'3','1.100');
In the above example, the task will be executed after 3000ms, or after time between 1900ms to 4100ms, among tasks in same time range.
Adding a Task with an Interval
Syntax: $setInterval(fn,interval,margin)
.
- Parameters
fn
- callback function to executefn(task)
- gets task as parameter
interval
- time or array of times in milliseconds or formatted string for timeToMS for task intervalmargin
- time in milliseconds or formatted string for timeToMS for task margin
- returns
- instance of
Task
- instance of
Interval example:
let count = 0;
const fn = (task) => {
if(count === 5) task.cancel()
console.log(`Task executed ${count} times!`);
count++
}
TimeManager.$setInterval(fn,1000);
In example above, the function will run 5 times each 1000ms.
Intervals example:
const fn = () => console.log('Task executed')
$setInterval(fn,[100,200,500,100])
In example above, task will run after 100ms, 200ms, 500ms and 100ms and then will stop.
Using margin
margin
parameter used for grouping tasks by time.
For example, you can set tasks with delay 1000ms, 980ms, 950ms and execute them together with 950ms by setting margin = 50
to all.
Here how it works:
- running task with 950ms
- looking for tasks satisfying the rule:
startTime <= 950 && endTime >= 995
- task with 980ms has range
930 - 1020
(980 ± 50) - satisfying the rule - task with 1000ms has range
950 - 1050
(1000 ± 50) - satisfying the rule
- task with 980ms has range
The end time is allways 5ms less for reinsurance.
Example:
for (let i = 1; i <= 5; i++) {
TimeManager.$setTimeout(() => console.log(i), i * 20,50)
}
In example above:
- Tasks 1,2,3 will be executed after 20ms
- Tasks 4,5 will be executed after 60ms
Resetting a Task
Task instance has reset method, which allows you to start over the countdown. It works with $setTimeout and $setInterval. In case of $setInterval, it reseting the current delay.
// using regular setTimeout for example only
const delay = (ms) => new Promise((resolve) => {setTimeout(() => resolve(), ms)})
let executed = false
const fn = () => {executed = true}
const task = TimeManager.$setTimeout(fn, 1000);
await delay(500)
task.reset()
await delay(500)
console.log(executed) // false
await delay(500)
console.log(executed) // true
In example above, reset method reseting the countdown to 1000ms after 500ms.
Canceling a Task
To cancel a task and prevent it from executing:
const fn = () => {console.log('Task executed!')}
const task = TimeManager.$setTimeout(fn, 1000);
task.cancel();
In the example above, task will be never executed.
Static methods and properties
Methods:
TimeManager.stop(); // Stops current setTimeout
TimeManager.run(); // Executes remaining tasks after stop
Task api
Each task
Properties:
fn
: the function for executiondelay
: current delay for taskmargin
: current margin for taskonCancel
: array of hooks for canceling taskonReset
: array of hooks for reseting taskintervals
: array of remainng intervals for taskinterval
: interval for task (or null)canceled
: true if cancled, false if not
Getters:
startTime
: calculated with margin startTimeendTime
:calculated with margin endTime
Methods:
reset()
: reseting countdown for taskcancel()
: canceling the taskupdateDelay(newDelay)
: updating task's delay