Javascript 0]['name']; var ip=行[0]['ip']; var迭代次数=行[0]['runs']; 进程标准设置编码('utf8'); 进程标准开启('data',函数(data){ var str=data.toString(); var s=str.split(“|”); var p=s[0]。拆分(“/”; var t=(s[1]==null)?“”:s[1]; 如果(p!=null&&s[0]!=“@”){//需要检查@,因为程序将此打印为第一行,这很好,那么我们只能执行一次进一步的查询。 //检查simc返回的数字,看看它完成了多少模拟人生 如果(parseInt(p[0])

Javascript 0]['name']; var ip=行[0]['ip']; var迭代次数=行[0]['runs']; 进程标准设置编码('utf8'); 进程标准开启('data',函数(data){ var str=data.toString(); var s=str.split(“|”); var p=s[0]。拆分(“/”; var t=(s[1]==null)?“”:s[1]; 如果(p!=null&&s[0]!=“@”){//需要检查@,因为程序将此打印为第一行,这很好,那么我们只能执行一次进一步的查询。 //检查simc返回的数字,看看它完成了多少模拟人生 如果(parseInt(p[0]),javascript,linux,node.js,daemon,child-process,Javascript,Linux,Node.js,Daemon,Child Process,因此,它将执行您的查询,然后等待10秒再触发另一个查询。不确定您是否在意-但您的IP正则表达式不是很准确-它将乐意接受999.999.999例如。因此,您希望执行db.query(“选择*FROM queue…并每10秒成功回调一次?Thanx对于提示Benjamin!setInterval是个坏主意,因为当前任务可能出于某种原因仍在运行,然后您会再次触发它。最好在成功时设置10秒的超时时间(这实际上不会导致每10秒执行一次,而是每10秒+经过的时间)或者测量从任务开始到任务完成所经过的时间,并

因此,它将执行您的查询,然后等待10秒再触发另一个查询。

不确定您是否在意-但您的IP正则表达式不是很准确-它将乐意接受
999.999.999
例如。因此,您希望执行
db.query(“选择*FROM queue…
并每10秒成功回调一次?Thanx对于提示Benjamin!
setInterval
是个坏主意,因为当前任务可能出于某种原因仍在运行,然后您会再次触发它。最好在成功时设置10秒的超时时间(这实际上不会导致每10秒执行一次,而是每10秒+经过的时间)或者测量从任务开始到任务完成所经过的时间,并使用时间差作为超时。可能我们需要一些变量作为锁来消除竞争条件?这样我就可以将代码封装在一个函数中运行它,在那里//你所有的工作都是检查返回,然后超时?我不完全确定你告诉我的是什么一个带有lastAsyncThing的脚本,因为脚本在不同的地方结束,这取决于程序是否成功。我应该把超时放在什么地方?@peter你对此有意见吗?
var spawn = require('child_process').spawn;
var mysql = require('mysql');
var JSFtp = require('jsftp');
var check = require('node-validator').check;
var sanitize = require('node-validator').sanitize;

//Setup the db connection
var db = mysql.createConnection({
  host : 'db',
  port : 3306,
  database: 'db',
  user : 'db',
  password : 'db'
});

//Make the connection
db.connect(function(err){
    if(err != null) {
        res.end('Error connecting to mysql:' + err+'\n');
    }
});

var die = function(msg){
    console.error(msg);
    process.exit(1);
}

function ip2long ( ip_address ) {
    var output = false;
    var parts = [];
    if (ip_address.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
        parts  = ip_address.split('.');
        output = ( parts[0] * 16777216 +
        ( parts[1] * 65536 ) +
        ( parts[2] * 256 ) +
        ( parts[3] * 1 ) );
    }
    return output;
}


db.query("SELECT * FROM queue WHERE cooldown > UNIX_TIMESTAMP(NOW()) AND simulated=0 ORDER BY cooldown DESC LIMIT 1", function(err, rows){
    if(err != null){
        die("Query error: " + err);
    }

    if(rows < 1){
        die("No rows");
    }

    //Set the vars from the query
    var name = rows[0]['name'];
    var ip = rows[0]['ip'];
    var iterations = rows[0]['runs'];

    var bin = "/home/hoar/sum/run"
    var args = ['arg='+name, 'arg2='+iterations, 'path=/var/www/upload/'+name+'.html', 'output=log.log'];
    var proc = spawn(bin, args);
    var time = "/.*/";
    var pct = "/^\d/";
    var name = rows[0]['name'];
    var ip = rows[0]['ip'];
    var iterations = rows[0]['runs'];

    proc.stdout.setEncoding('utf8');
    proc.stdout.on('data', function(data) {
        var str = data.toString();
        var s = str.split("|");
        var p = s[0].split("/");
        var t = (s[1] == null) ? "" : s[1];

        if(p != null && s[0] != "@"){ //Needed to check for @ because the program prints this as first line, which is good then we can do the query further done only once.
            //Check the return numbers from simc to see how many sims it has done
            if(parseInt(p[0]) < parseInt(p[1])){ 
                //Check if the 6th match is a number and the 7th only contains letters
                if(t != null){ 
                    var time = t.replace(/(\r\n|\n|\r)/gm,""); //Remove any line disturbers for db

                    //Update the database with the amount of time left on the simulation
                    db.query("UPDATE `queue` SET `status`=" + db.escape(time) + " WHERE (`name`=" + name + ")");
                    //console.log(p[0]+"/"+p[1] + " - " + t + " left");
                }
                //console.log(p[0]+"/"+p[1] + " iterations done");
            }
        }else{
            //If the stdout is null run this query since we don't want to run this more than once.
            db.query("UPDATE `queue` SET `simulated`='2' WHERE (`name`=" + name + " AND simulated!='2')");
            //console.log("Updated db to 2");
        }
    });

    proc.stderr.on('data', function (data) {
        var str = data.toString();
        //If the program returns stderr we want to make sure it stops and we update the database to let the user know.
        if(str.indexOf("ERROR! Setup failure...")){ 

            //Update the database with the amount of time left on the simulation
            db.query("UPDATE `queue` SET `simulated`='3' WHERE (`name`=" + name + ")");

            //Kill the DB connection
            db.destroy(); 
            die("There was an error: " + data);
        }
    });

    proc.on('exit', function (code) {
    //Setup the ftp connection
    var ftp = new JSFtp({
      host: "ftp",
      port: 21,
      user: "ftp",
      pass: "ftp"
    });

        //Simulation ended with success update the database and kill.
        db.query("UPDATE `queue` SET `simulated`='1' WHERE (`name`=" + name + " AND simulated='2')");

        ftp.put('/var/www/upload/'+rows[0]['name']+'.html', 'public_html/mysite/'+ip2long(rows[0]['ip'])+'/'+rows[0]['name']+'.html', function(hadError) {
          if (!hadError)
            console.log("FTP error");

            ftp.raw.quit();
        });
        db.destroy(); 
        //die("Simulation is done");
    });

});//end sql
$ forever script.js
setInterval(function(){...}, 10*1000);
function doMainStuff() {
  //do all your stuff
  lastAsyncThing(function (error) {
    //When your final async thing is done, start the timer
    if (error) {
        //log error. Maybe exit if it's irrecoverable.
    }
    setTimeout(doMainStuff, 10 * 1000);
  });
}

//when your program starts, do stuff right away.
doMainStuff();
function mydbquery(callback) {
    db.query("SELECT * FROM queue WHERE cooldown > UNIX_TIMESTAMP(NOW()) AND simulated=0 ORDER BY cooldown DESC LIMIT 1", function(err, rows){
    if(err != null){
        die("Query error: " + err);
    }

    if(rows < 1){
        die("No rows");
    }

    //Set the vars from the query
    var name = rows[0]['name'];
    var ip = rows[0]['ip'];
    var iterations = rows[0]['runs'];

    var bin = "/home/hoar/sum/run"
    var args = ['arg='+name, 'arg2='+iterations, 'path=/var/www/upload/'+name+'.html', 'output=log.log'];
    var proc = spawn(bin, args);
    var time = "/.*/";
    var pct = "/^\d/";
    var name = rows[0]['name'];
    var ip = rows[0]['ip'];
    var iterations = rows[0]['runs'];

    proc.stdout.setEncoding('utf8');
    proc.stdout.on('data', function(data) {
        var str = data.toString();
        var s = str.split("|");
        var p = s[0].split("/");
        var t = (s[1] == null) ? "" : s[1];

        if(p != null && s[0] != "@"){ //Needed to check for @ because the program prints this as first line, which is good then we can do the query further done only once.
            //Check the return numbers from simc to see how many sims it has done
            if(parseInt(p[0]) < parseInt(p[1])){ 
                //Check if the 6th match is a number and the 7th only contains letters
                if(t != null){ 
                    var time = t.replace(/(\r\n|\n|\r)/gm,""); //Remove any line disturbers for db

                    //Update the database with the amount of time left on the simulation
                    db.query("UPDATE `queue` SET `status`=" + db.escape(time) + " WHERE (`name`=" + name + ")");
                    //console.log(p[0]+"/"+p[1] + " - " + t + " left");
                }
                //console.log(p[0]+"/"+p[1] + " iterations done");
            }
        }else{
            //If the stdout is null run this query since we don't want to run this more than once.
            db.query("UPDATE `queue` SET `simulated`='2' WHERE (`name`=" + name + " AND simulated!='2')");
            //console.log("Updated db to 2");
        }
    });

    proc.stderr.on('data', function (data) {
        var str = data.toString();
        //If the program returns stderr we want to make sure it stops and we update the database to let the user know.
        if(str.indexOf("ERROR! Setup failure...")){ 

            //Update the database with the amount of time left on the simulation
            db.query("UPDATE `queue` SET `simulated`='3' WHERE (`name`=" + name + ")");

            //Kill the DB connection
            db.destroy(); 
            die("There was an error: " + data);
        }
    });

    proc.on('exit', function (code) {
        //Setup the ftp connection
        var ftp = new JSFtp({
          host: "ftp",
          port: 21,
          user: "ftp",
          pass: "ftp"
        });

        //Simulation ended with success update the database and kill.
        db.query("UPDATE `queue` SET `simulated`='1' WHERE (`name`=" + name + " AND simulated='2')");

        ftp.put('/var/www/upload/'+rows[0]['name']+'.html', 'public_html/mysite/'+ip2long(rows[0]['ip'])+'/'+rows[0]['name']+'.html', function(hadError) {
          if (!hadError)
            console.log("FTP error");

            ftp.raw.quit();
        });
        db.destroy();

        //die("Simulation is done");
//NEW CODE!!! 
        callback();
//END OF NEW CODE
    });

});//end sql
}

//NEW CODE!!!
function wait10sec(){
    setTimeout(function(){
        mydbquery(wait10sec);
    }, 10000);
}

mydbquery(wait10sec);
//END OF NEW CODE