how to make a tracking timer in command line with node.js - node.js

I am trying to build a simple time tracking tool in the command line and and basically i want to run start and stop commands and output the time elapsed. At the moment I am having problems because my timer variable is not holding values between requests. This is the simple script I have wrote until now;
Do I need to spawn another process or should I just store the start time in a .txt file or database and use it from there?
#! /usr/bin/env node
var cli = require('commander'),
time,
timer = null;
cli
.version('0.0.1');
cli
.command('start')
.description('Start timer')
.action(start);
cli
.command('stop')
.description('Stop timer')
.action(stop);
cli.parse(process.argv);
function start() {
timer = new Date;
}
function stop() {
time = new Date - timer;
hours = Math.floor(time/3600);
seconds = time % 3600;
minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
seconds = Math.floor(seconds);
console.log(hours + ' hours ' + minutes + ' minutes ' + seconds + " seconds")
}

Without some external mechanism for storing state of ay kind (such as a database, flat file, etc) each invocation of your program will have no knowledge of what happened in any other invocation of it.
Each time you run the application all the variables are initialized, written to, read from, etc and then once your application stops everything is then binned, any memory it has used is returned to the operating system and all your variables disappear.
The simplest way to persist time would probably to have your code read and write to a flat file (maybe in a json format). This does have potential issues such as concurrency and file locking but I wouldn't worry about this till they actually become a problem. (and then you can just use a database etc).

Related

Vanilla NodeJS Cron Job?

I want to do something in node at, say, midnight each day.
I see a lot of stuff pointing me to node-cron, and I see this article configuring a docker container to execute a script per a crontab
I want to 1. not use any external packages and 2. keep the script being executed inside the server code itself (i.e. I couldn't have the docker container execute some other file on a schedule)
The use case is I want to update a cache on the server every day around midnight, and then, at more frequent intervals, use that cache for various things.
You can use setInterval to run the code every hour and check if it's around midnight
setInterval(() => {
if (new Date().getHours() === 0) {
// do stuff
}
}, 1000 * 60 * 60 * 60)

How to complete a process in Node JS after executing all the operations

I am very new to NodeJS and trying to develop an application which acts as a scheduler that tries to fetch data from ELK and sends the processed data to another ELK. I am able to achieve the expected behaviour but after completing all the processes, scheduler job does not exists and wait for another scheduler job to come up.
Note: This scheduler runs every 3 minutes.
job.js
const self = module.exports = {
async schedule() {
if (process.env.SCHEDULER == "MinuteFrequency") {
var timenow = moment().seconds(0).milliseconds(0).valueOf();
var endtime = timenow - 60000;
var starttime = endtime - 60000 * 3;
//sendData is an async method
reports.sendData(starttime, endtime, "SCHEDULER");
}
}
}
I tried various solutions such Promise.allSettled(....., Promise.resolve(true), etc, but not able to fix this.
As per my requirement, I want the scheduler to complete and process and exit so that I can save some resources as I am planning to deploy the application using Kubernetes cronjobs.
When all your work is done, you can call process.exit() to cause your application to exit.
In this particular code, you may need to know when reports.sendData() is actually done before exiting. We would have to know what that code is and/or see the code to know how to know when it is done. Just because it's an async function doesn't mean it's written properly to return a promise that resolves when it's done. If you want further help, show us the code for sendData() and any code that it calls too.

how to run a line of code after a delay in a paralel thread node js?

I need to schedule one of the tasks in a web site while being able to use the rest of the website features
I'm reading about async and sync execution but not sure if there is a simpler way to do it.
This task is sending something to the Windows cmd to run a program, so I thought about two options:
Adding a command in the cmd sentence to delay the execution of the line
Defining this line of code as a thread which includes a "wait" action with the specificed delay
I'm trying this code:
var schedule = require('node-schedule');
schedule.scheduleJob('6 * * * *', function(){
//console.log('The answer to life, the universe, and everything!');
command += "--test project://" + projectName + "/" + tc.name + " ";
});
This runs the command in minute 6.
I'm a bit newbie in the language, so I'm not sure if this is the best way to do it.
What do you guys think? Any node js function I could use?

Why ( new Date() ).toString() is so slow in Node.js?

I am playing a bit with Node.js. I've just started writing something new and it stuck me that my simple "console" app takes quite long to respond. This app loads a 5MB json file, turns it into an object but all that still does not take a significant amount of time. My further search (in a quite short and simple code) led me to conclusion that this single line:
this.generated_on = ( new Date() ).toString();
takes around 2.5s to execute. Further investigation made me understand even less. I've modified it to:
this.generated_on = new Date();
this.generated_on = this.generated_on.toString();
(with console.timeLogs in between) and line with toString() was the one that took over 2 seconds to execute. Then, I've modified the code once again:
this.generated_on = new Date('2019-02-04 20:00:00');
this.generated_on = this.generated_on.toString();
and results were other way around. toString() took only 2ms while creating Date object took over 2s.
Why is it so slow? Why so different results? Any faster way to get formatted current time string? (I don't care much about execution time for this project as it works offline, still it bugs me).
I think your development environment is off or something. I cannot tell you why your machine is running the code in a slow manner. I cannot replicate the problem you were saying.
I tried to benchmark the code you have above.
https://repl.it/#act/HotpinkFearfulActiveserverpages
Go here and try clicking on Run button at the top.
Here's the result I am seeing
// Case Togehter:
// this.generated_on = ( new Date() ).toString();
// Case Separately:
// this.generated_on = new Date();
// this.generated_on = this.generated_on.toString();
Together x 332,222 ops/sec ±7.75% (44 runs sampled)
Separtely x 313,162 ops/sec ±8.48% (43 runs sampled)
332,222 ops/sec means an operation took 1/332,222 seconds on average.
I suggest you to use node.js builtin module 'Performance hooks'.
You can find documentation here: https://nodejs.org/dist/latest-v11.x/docs/api/perf_hooks.html#perf_hooks_performance_mark_name
Mark each process from top to bottom and then print the metrics (in milliseconds), you will figure out the actual issue

Matlab timer is not executed asynchronously [duplicate]

I am trying to print a warning or just a message after every second, like "1 second elapsed".
Is there a possibility to realize that?
I tried it with tic toc and a loop, but it is pretty insufficient. Furthermore I never get exactly one second. Is there a command that prints every X ms automatically?
Any ideas?
Thanks in advance.
Use a timer object.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = 1;
t.TimerFcn = #(~,~)disp('1s elapsed');
start(t)
As #Daniel suggested, timer objects are the way to go.
One thing to remember is that MATLAB timers execute asynchronously but are not truly parallel (even though timer objects run in a different thread, the MATLAB interpreter is still single-threaded).
So timer events might not fire (BusyMode property defaults to drop) it they occur during certain lengthy non-interruptible operations (like builtin functions, MEX-functions, etc..).
Here is an example:
>> t = timer('ExecutionMode','fixedRate', 'Period',1, 'BusyMode','drop', ...
'TimerFcn',#(~,~)disp(datestr(now,'MM:SS')));
>> start(t)
35:21
35:22
35:23
>> eig(rand(2000)); % <-- takes a couple of seconds to finish
35:27
35:28
35:29
35:30
>> stop(t)
Note how the timer event did not get a chance to execute while the EIG function was running.
Now if we change the BusyMode property to queue, then once again the event will not fire during the execution of EIG operation, but will immediately spit out all the queued events once EIG finishes:
>> t.BusyMode = 'queue';
>> start(t)
37:39
37:40
>> eig(rand(2000));
37:45
37:45
37:45
37:45
37:45
37:46
37:47
>> stop(t)
>> delete(t)
It is called pause. The optional argument specifies the duration in seconds. Documentation: http://www.mathworks.de/de/help/matlab/ref/pause.html

Resources