NetSuite Scheduled Script "Sleep" - javascript

I have read several posts about doing "sleep" or "wait" in Javascript. However, they all use client side Javascript. I need to do this in a Scheduled NetSuite SuiteScript. I ahve tried setTimeout() and it tells me it cannot find the function (as well as window.setTimeout()).
If I have to do an infinite loop with an if condition that gives me the delay I want, i will do that but it is less than ideal. I want to know if there is a simple "sleep" or "wait" kind of way of doing this to delay code from executing.
My purpose is because my code deletes records. In my current setup, if 2 of these records are deleted too close to one another NS throws "unexpected error" and stops. if there is a long enough pause in between, then it works. I am trying to automate this so i don't sit here deleting records all day.
The posts I have checked so far:
How to create javascript delay function
JavaScript.setTimeout
JavaScript sleep/wait before continuing
What is the JavaScript version of sleep()?
Mine is not a duplicate to any of those as they all assume Client side and are not specific to NetSuite SuiteScript. Thanks!

Doing a loop based wait might be an overhead, as at times NetSuite might warn of number of script statement.
Another way of doing a sleep can be using nlapiRequestURL() and writing a service on your web server, as it is blocking and synchronous on server side. You can write a HTTP service and in your web server do the sleep job and then respond to the client.

If you are deleting records in a scheduled script then those run serially. Have you tried wrapping the nlapiDeleteRecord call in a try-catch?
If you are getting an error then is a User Event or workflow script running and throwing the error?
As far as a wait I've done the following. It runs the risk of throwing a too many instructions error but avoids a database call that would eat governance. If you can find an nice API call with 0 governance cost that eats some time that would be better but this worked well enough for me.
function pause(waitTime){ //seconds
try{
var endTime = new Date().getTime() + waitTime * 1000;
var now = null;
do{
//throw in an API call to eat time
now = new Date().getTime(); //
}while(now < endTime);
}catch (e){
nlapiLogExecution("ERROR", "not enough sleep");
}
}

Related

PHP altetrnative way how to timeout

i am making a tool where user can provide a delay time of response. It should be easy to do however when I used set_time_limit from doc
Warning: set_time_limit() has been disabled for security reasons
From error and by googling a bit it's obvious that hosting provider disable this functionality in PHP.
Question:
However I want to ask you if there is some alternative way how to timeout response using php without this function.
I can imagine this can be done via pass this timeout value to JS and timeout it via that but I hope if there isn't some other soluction for this.
The only idea I had is to put in your script some "waypoints" where you check the execution time, and if the execution time is too long terminate the script using die(), to check the execution time you can use new DateTime("now"); at every "waypoint" and then something like $interval = $datetime1->diff($datetime2); to get the interval between the first time you had and the last one

How to Long Poll in NodeJS / Javascript?

Just to be clear my understanding of long polling is that you make request to a server on a time interval.
I am trying to implement a bitcoin purchasing system that checks the blockchain for change in my wallets balance. I know there are websockets that do this but I have to wait for 1 confirmation to receive an update and the REST API offers more flexibility, so I would just prefer to make a request to the server every 5 seconds or so and check each response for a change in my balance then go from there.
The issue is I can't seem to figure out how to do this in NodeJS. Functionially this is how I imagine my code.
Get current balance (make request)
Get current balance again (make request)
Check if there is a difference
**If not**
wait 5 seconds
Get current balance
Check for difference
repeat till different (or till timeout or something)
If different
do some functions and stop checking balance.
I've been trying to do each step but I've gotten stuck at figuring out how to create a loop of checking the balance, and stopping the loop if it changes.
My original thought was to use promises and some for loops but that doesn't materialize.
So now I am asking for your help, how should I go about this?
One way to do this would be to setup a setInterval timer to kickoff a request every x seconds. By setting some logic after the response you can then choose to de-reference the timer and trigger another function. Here's a snippet. You'll notice I set a variable to reference the timer, and then de-reference it by setting it to null, where then the GC is smart enough to release. You may also use the 'clearTimeout' function, which is perhaps the better way to go.

Alternatives to executing a script using cron job every second?

I have a radio station at Tunein.com. In order to update album art and artist information, I need to send the following
# Update the song now playing on a station
GET http://air.radiotime.com/Playing.ashx?partnerId=<id>&partnerKey=<key>&id=<stationid>&title=Bad+Romance&artist=Lady+Gaga
The only way I can think to do this would be by setting up a PHP/JS page that updates the &title and &artist part of the URL and sends it off if there is a change. But I'd have to execute it every second, or at least every few seconds, using cron.
Are there any other more efficient ways this could be done?
Thank you for your help.
None of the code in this answer was tested. Use at your own risk.
Since you do not control the third-party API and the API is not capable of pushing information to you when it's available (an ideal situation), your only option is to poll the API at some interval to look for changes and to make updates as necessary. (Be sure the API provider is okay with such an approach as it might violate terms of use designed to prevent system abuse.)
You need some sort of long-running process that will execute at a given interval.
You mentioned cron calling a PHP script which is one option (here cron is the long-running process). Cron is very stable and would be a good choice. I believe though that cron has a minimum interval of 1 minute. I'm sure there are similar tools out there, but those might require you to have full control over your server.
You could also make a PHP script the long-running process with something like this:
while(true){
doUpdates(); # Call the API, make updates, etc
sleep(5); # Wait 5 seconds
}
If you do go down the PHP route, error handling of some sort will be a must:
while(true){
try{
doUpdates();
} catch (Exception $e) {
# manage the error
}
sleep(5);
}
Personal Advice
Using PHP as a daemon is possible but it is not as well tested as the typical use of PHP. If this task was given to me, I'd write a server/application in JavaScript using Node.js. I would prefer Node because it is designed to work as a long running process and intervals/events are a key part of JavaScript and I would be more confident in that working well than PHP for this specific task.

The model of JavaScript function executing

Does JSVM run just in one thread?
I am wondering how the JavaScript function executing inside the VM.
The source code below is interesting:
// include jQuery as $
function test() {
$.ajax({url:"xxx.com"})
.success(function() {alert("success 1");})
.fail(function() {alert("fail 1");});
$.ajax({url:"yyy.com"})
.success(function() {alert("success 2");})
.fail(function() {alert("fail 2");});
while(true);
}
It will make die loop at the "while" line and never pop up any alert dialog to show neither "success" nor "fail".
We know inside the $.ajax, the VM creates XMLHttpRequest and sends a HTTP request.
After sending out two requests, it meets the "while" line.
Thus I image that the JSVM:
1) can handle only function call at one time. (function is atomic)
2) follow the rule: first comes, first served.
Does my idea right?
Does anyone can explain the internal implementation of JSVM?
More specific,
If using AngularJS to develop a front end app, we would like to do something and then immediately record a log to remote server in form submit event like ng-submit.
function ngSubmitTest() {
doA();
recordA(ajax, remoteServer); // must after doA()
}
If recordA uses AJAX, we should ensure recordA is complete before ng-submit redirect the page meanwhile kill the old page and also the VM (if the old page is killed, the recordA may not complete). One solution is doing AJAX with async=false. And I wonder if there is any other solutions?
Thanks.
The implementation of JS depends on the context you're runing it.
Each browser has it's own implementantion, and they can do whatever they want as long as they follow the language specification.
It shouldn't bother you if it runs on one or multiple threads, but you can be sure JavaScript is not a "threaded" language, it works with an event loop flow, in which an event is fired, and consecutive functions are fired after that, until there is nothing more to call. This is the reason why it's pretty hard to block the UI in JavaScript if you're writing "good" code.
A good example on how this works, and the diferences betwen event loops and classic threading, is node.js, i'll give you a example:
Supose you're listening for a request on a server, and 2 seconds after the request arrives you'll send a message. Now let's supose you duplicate that listener, and both listeners do the same thing. If you request the server, you'll get the two messages at the same time, 2 seconds after the request is made, instead of one message on 2 seconds, and the other one on 4 seconds. That means both listeners are runing at the same time, instead of following a linear execution as most systems do.
Node runs Chrome's V8 if you're wondering, it's a very professional JS interpreter and it was a breakthorugh when it came out.

Reducing Javascript CPU Usage

I'm planning on writing some code for encrypting files in javascript locally. For large files and large key sizes, the CPU usage (naturally) is pretty high. In a single script design, this often hangs the browser until the task is complete.
In order to improve responsiveness and allow users to do other things in the mean time I want to try make the script 'friendlier' to the user's PC. The encryption process will be reading a file as a binary string and then encrypting the string in chunks (something like 1KB/chunk - needs testing). I want to try and user HTML5-based workers to make the whole thing as incremental as possible. Something like:
Spawn worker
Send worker a binary data chunk
Worker completes encryption, passes back new chunk
Worker dies.
This might also help with multicore processors, by having multiple workers alive at once.
Anyway, has anybody looked at deliberately slowing down a script in order to reduce CPU usage? Something like splitting the worker's encryption task into single operations, and introducing a delay between them.
Interval timer callback every 100ms (example).
Is worker busy?
Yes - Wait for another interval
No - Start encrypting the next letter
Advice/thoughts?
Does anyone have experience using workers? If you seperate the main UI from intensieve work by making it a worker, does the responsiveness increase?
This doesn't utilize anything HTML5, but here's an example for calling a function every N milliseconds, assuming you can determine an appropriate wait time. Basically, I'm trying to help you by showing you a way to enforce stalling some amount of time before doing more processing.
function doSomething(){
clearTimeout(timeout);
// do your "expensive" processing
// ...
// decide the job is done and return here or else
// call doSomething again in sleepMS milliseconds
timeout = setTimeout(doSomething,sleepMS);
}
var timeout;
var sleepMS = 1000;
doSomething();
EDIT
changed last line from
var timeout = setTimeout(doSomething,1000);
to just this
doSomething()
EDIT 2
Changed 1000 to sleepMS in setTimeout call, duh :)

Categories