add sleep() and sleep command

This commit is contained in:
Lisa Milne 2023-12-14 16:10:00 +10:00
parent 13113b59d5
commit 409470d0bc
3 changed files with 57 additions and 2 deletions

View file

@ -1535,6 +1535,53 @@ Options:
return main(args);
});
clite.commands.load('sleep',function(args,env,io) {
var stdio = io.include('stdio');
var stdlib = io.include('stdlib');
function help() {
stdio.printf(`
sleep - suspend execution for a time
Usage: sleep [OPTION] <SECONDS>
Options:
-? Print this help information
`);
}
function scb(r) {
io.exit(0);
}
function main(args) {
var seconds = 0;
for (var i=1; i<args.length; i++) {
if (args[i][0] == '-') {
for (var j=1; j<args[i].length; j++) {
switch (args[i][j]) {
case '?':
help();
return 0;
break;
default:
stdio.fprintf(io.stderr,'unknown argument: -%c\n',args[i][j]);
}
}
}else{
seconds = parseInt(args[i]);
}
}
if (seconds < 1)
return 0;
if (!stdlib.sleep(seconds,scb))
return 1;
return null;
}
return main(args);
});
if (window.location.protocol == 'file:')
clite.commands.load('test',function(args,env,io) {
var stdio = io.include('stdio');

View file

@ -32,9 +32,11 @@ var clite = {
}
return true;
},
execSafeAsync:function(f) {
execSafeAsync:function(f,delay) {
if (typeof delay !== 'number')
delay = 10;
try{
setTimeout(f,10);
setTimeout(f,delay);
} catch(e) {
clite.log.write(e.message);
return false;

View file

@ -92,6 +92,12 @@ return Object.create({
// wait for all child processes to exit
waitall:function(cb) {
return clite.proc.addWaitGroupAll(io.pid,cb);
},
sleep:function(seconds,cb) {
return clite.core.execSafeAsync(function() {
cb(0);
},seconds*1000);
}
});