how to exit casperJS script when it takes more than 60 seconds? - casperjs

Sometimes the first inscruction of the casperJS never end:
casper.start(url, function() {
console.log('start', url, email, name);
// sometimes it never steps here !!
});
So the goal would be to exit the script if it takes>30 seconds for isntance.
Any idea ?
I tried with:
waitTimeout: 30000,
stepTimeout: 30000,
onStepTimeout: function(self) {
self.exit();
}
But this did not help

There is a sort of hack to exit CasperJS immediately, try it:
function exit() {
var exitTime = new Date();
console.log('Exiting. Elapsed from start, ms: ' + (exitTime - startTime));
casper.exit();
casper.bypass(1);
}
var startTime = new Date();
console.log('Setting exit timeout at ' + startTime);
setTimeout(exit, 30000); // milliseconds

Related

How to get time when session starts and finishes?

I have a task to get the time when the session starts and finishes in Laravel.
Is it I should use Laravel Websockets to accomplish this task of maybe Pusher?
What technology should I dive deeper into?
I think you don't need to go to Websockets or Pusher, you just need simple setInterval function to display session out time. And you will get session out time from session.php file inside config folder 'lifetime' => 120, here 120 is minutes.
var sessionOutTimeInSeconds = 120 *60;
setInterval(function(){
sessionOutTimeInMinutes -= 1;
}, 1000);
var sessionOutTimeInMinutes = 2;// here your can set 120
var sessionOutTimeInSeconds = sessionOutTimeInMinutes * 60;
var timeStr = 'Expire in 120 Minutes';
var alertBefore = 1;
var intervalId = setInterval(function(){
sessionOutTimeInSeconds -= 1;
sessionOutTimeInMinutes = parseInt(sessionOutTimeInSeconds/60);
timeStr = '';
// **here you can do any stuff when you got session out. may be you can redirect go to home page to go to login page.**
if(sessionOutTimeInSeconds > 0 ){
if(sessionOutTimeInMinutes >= alertBefore){
timeStr = '<span style="color:green;">';
}else{
timeStr = '<span style="color:red;">';
}
timeStr += 'Expire in '+ sessionOutTimeInMinutes + ' Minutes ' + (sessionOutTimeInSeconds%60) + ' Seconds';
}else{
//alert('Session Expired.');
//clearInterval(intervalId);
timeStr = '<span style="color:red;">';
timeStr += 'Session Expired '+ (-1)*sessionOutTimeInMinutes + ' Minutes ' + (-1)*(sessionOutTimeInSeconds%60) + ' Seconds ago.';
}
timeStr += '</span>';
document.querySelector('#sessionout').innerHTML = timeStr;
}, 1000);
<div id="sessionout"></div>
to get session start time:
if (!isset($_SESSION['started'])) {
$_SESSION['started'] = $_SERVER['REQUEST_TIME'];
}
I'm not sure how to do session end time, but maybe you can use the same logic for it. Maybe this thread could be of some assistance for that: When does a PHP session end?

jQuery deferred promise progress notification

I've been playing with promises and trying to build some sort of progress notification.
The code is executing all functions in the right order, but the progress updates execute just before the resolve as opposed to when they actually happen.
Can anyone point out what I'm doing wrong?
function start(x) {
console.log("Start: " + x);
var promise = process(x);
console.log("promise returned");
promise.then(function(data) {
console.log("Completed: " + data);
}, function(data) {
console.log("Cancelled: " + data);
}, function(data) {
console.log("In Progress: " + data);
});
}
function process(x) {
var deferred = $.Deferred();
var promise = deferred.promise();
// process asynchronously
setTimeout(function() {
for (var i=0 ; i<x ; i++) {
sleep(1000);
deferred.notify(i);
}
if (x % 2 === 0) {
deferred.reject(x);
} else {
deferred.resolve(x);
}
}, 0);
return promise;
}
function sleep(sleepDuration) {
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
start(3);
Fiddle here:
https://jsfiddle.net/n86mr9tL/
A delay timer implemented with while(), will "block" - ie hog the processor.
Blocking not only prevents other javascript from running but also inhibits reliable refreshing of the browser screen including the console. So whereas those deferred.notify(i) and console.log("In Progress: " + data) statements are firing, the console isn't refreshed until the processor becomes free to do so.
Unsurprisingly, the solution lies in not using while().
Fortunately, javascript imcludes two built-in methods window.setTimeout() and window.setInterval(), which are conceptually different from a while() idler but fulfil the same role .... without blocking.
window.setInterval(fn, t) fires function fn every t milliseconds,
window.setTimeout(fn, t) fires function fn once, after t milliseconds.
Both methods return an opaque reference, which allows them to be cancelled.
In the code below, start() is unmodified, process() is heavily modified and sleep() has disappeared.
process() now does the following :
creates a jQuery Deferred and returns a promise derived from it,
establises a setInterval() of 1000 milliseconds (1 second), whose function :
keeps count of how many times it has been called,
calls deferred.notify() every second until the counter i reaches the specified maximum x,
when the specified maximum is reached :
the interval, which would otherwise silently tick away ad infinitum, is cleared,
deferred.resolve() or deferred.reject() are called to settle the Deferred (and its promise),
function start(x) {
console.log("Start: " + x);
process(x).then(function(data) {
console.log("Completed: " + data);
}, function(data) {
console.log("Cancelled: " + data);
}, function(data) {
console.log("In Progress: " + data);
});
}
function process(x) {
return $.Deferred(function(dfd) {
var i = 1;
var intervalRef = setInterval(function() {
if(i < x) {
dfd.notify(i++);
} else {
clearInterval(intervalRef);
dfd[(x % 2 === 0)?'reject':'resolve'](x);
}
}, 1000);
}).promise();
}
console.clear();
start(3);
Updated fiddle

socket.on fire only after page reload

My client socket.on doesn't fire after calling the server ( socket.emit ('callserver'). However, when I refresh the page, it works! I'm not sure I understand this correctly. Any idea why this is the case? thanks ahead for any input!
Here's my code for the client:
socket.on('pauseTimeClock', function (data) {
stopWatchClock.setPausedTime(data.time);
$('.pauseTime').html(data.time.replace(/(\d)/g, '<span>$1</span>'))
console.log(stopWatchClock.pausedTime);
});
this.pause = function (stopwatch) {
this.stopwatch = stopwatch;
socket.emit('pauseTime');
this.stopwatch.changeState(this.stopwatch.getPauseState());
}
On the server:
socket.on('pauseTime', function () {
//stop broadcasting countDown time
clearInterval(timeinterval);
var pausedTime = moment();
function pauseTimeClock() {
var timeDiffHour = moment().hour() - pausedTime.hour();
var timeDiffMinute = moment().minute() - pausedTime.minute();
var timeDiffSec = moment().second();
var displayTime = timeDiffHour + ":" + timeDiffMinute + ":" + timeDiffSec;
socket.broadcast.emit("pauseTimeClock", { time: moment(displayTime, 'hhmm').format('HH:mm') });
}
setInterval(pauseTimeClock, 1000);
})
After monkeying around, I found that socket.broadcast.emit broadcasts to all client except the newly created one, whereas socket.emit broadcasts to everyone.

delete objects inParse after a set amount of time from a specific class

Hello I have an app that would upload photo's to the sever. Parse only gives us 20gb for storage and so I don't want to go over that limit. I want the server so that it would delete the files if it is 3 days old. So this is the code
Parse.Cloud.job('deleteOldPosts', function(request, status) {
// All access
Parse.Cloud.useMasterKey();
var today = new Date();
var days = 10;
var time = (days * 24 * 3600 * 1000);
var expirationDate = new Date(today.getTime() - (time));
var query = new Parse.Query('post');
query.lessThan('createdAt', expirationDate);
query.find().then(function (posts) {
Parse.Object.destroyAll(posts, {
success: function() {
status.success('All posts are removed.');
},
error: function(error) {
status.error('Error, posts are not removed.');
}
});
}, function (error) {});
});
However If I use this code it would delete files from all classes. I just want this code to work on only one class. Is it possible to do so?
When deleting objects in cloud code, use query.each instead of query.find to ensure that you delete all objects matching the query .
find has the query limitation of 100 objects returned by default (or up to 1000 if limit is used). Source
Below is your updated code using a promise chain which calls destroy on each Post object. When all of the destroy promises have completed, the success status will be reached, and if any of the destroys fail then the error status will be reached.
Parse.Cloud.job('deleteOldPosts', function(request, status) {
// All access
Parse.Cloud.useMasterKey();
var today = new Date();
var days = 10;
var time = (days * 24 * 3600 * 1000);
var expirationDate = new Date(today.getTime() - (time));
var query = new Parse.Query('post');
query.lessThan('createdAt', expirationDate);
query.each(function(post) {
return post.destroy();
}).then(function() {
console.log("Delete job completed.");
status.success("Delete job completed.");
}, function(error) {
alert("Error: " + error.code + " " + error.message);
status.error("Error: " + error.code + " " + error.message);
});
});

Timeout fails to change flag used in while loop

I'm trying to emulate a synchronous ajax call by blocking for a short period of time and then flipping a flag in the AJAX return. But the flags don't get updated, even though the time limit is reached. Instead the browser just hangs. I've tested in Firefox and Safari with the same results.
Broken design:
function syncAjax(args, timeLimit) {
var obj = {},
outOfTime = false,
timeout, k,
response = {returned: false, failed: false, responseText: null};
timeout = window.setTimeout(function() {
outOfTime = true;
}, timeLimit);
for(k in args) {
if(args.hasOwnProperty(k)) {
obj[k] = args[k];
}
}
obj.success = function(responseText) {
window.clearTimeout(timeout);
response.returned = true;
response.responseText = responseText;
};
obj.failure = function() {
window.clearTimeout(timeout);
response.returned = true;
response.failed = true;
};
// obj["async"] = true; // (automatically async)
$.ajax(obj);
// insert spinner timeout
while(true) {
if(response.returned || outOfTime) break;
}
return response;
}
Sample usage:
function doIt() {
var response = syncAjax({
url: "webpage.php",
data: {x: 5},
}, 500);
if(!response.returned) {
// do time out stuff
} else if(response.failed) {
// do failed stuff
} else {
console.log(response.responseText);
// do success stuff with response.responseText
}
}
// !! executing this function will lock up your browser !!
// doIt();
javascript cannot call your timeout until you return from your function. setTimeout is not a threaded call.
You could do this for your loop:
var start = Date().getTime();
while( start+timeLimit > Date().getTime() ) ;

Resources