简体   繁体   English

用于调用自身的函数的 NodeJS 计时器

[英]NodeJS timer for function that calls itself

I've got a Discord Bot and I want to check the database I'm using every a certain time looking for something.我有一个 Discord Bot,我想每隔一段时间检查一下我正在使用的数据库,以寻找一些东西。 So, I added this on my app.js:所以,我在我的 app.js 上添加了这个:

setTimeout(functions.verifyEmptyTeams, 864000)

The thing is that after that time (the time in miliseconds is just for testing) it runs the fuction once and it loops.问题是在那段时间之后(以毫秒为单位的时间仅用于测试)它运行一次函数并循环。 I added that same line at the end of the function so it does the same on loop.我在函数的末尾添加了相同的行,因此它在循环中执行相同的操作。 The function is:功能是:

    verifyEmptyTeams: function verifyEmptyTeams(){
        console.log('Verifying Empty Teams');
        let getTeams = 'SELECT * FROM teams';
        let i = 0;
        con.query(getTeams, function(err, teamResults){
          if(err) return handleDisconnect();
          for (rowDataPacket in teamResults){
            let teamOwner = teamResults[i].teamOwner;
            let tournamentID = teamResults[i].tournamentID;
            let getPlayers = 'SELECT * FROM players WHERE teamOwner = ? and tournamentID = ?';
            let data = [teamOwner, tournamentID];
            con.query(getPlayers, data, function(err, resultPlayers){
                if(err) console.log(err);
                if(resultPlayers.length == 0){
                    let deleteTeam = 'DELETE FROM teams WHERE teamOwner = ? and tournamentID = ?'
                    con.query(deleteTeam, data, function(err){
                        if(err) console.log(err);
                    })
                }
            })
          }
        })
        setTimeout(verifyEmptyTeams(), 864000)
    }

Edit: Just to be more clear.编辑:只是为了更清楚。 It loops inmediatly instead of waiting the 15 minutes again.它立即循环而不是再次等待 15 分钟。

Your recursive call's syntax is incorrect:您的递归调用的语法不正确:

setTimeout(verifyEmptyTeams(), 864000)

What this does is it invokes verifyEmptyTeams immediately , then passes its return value to setTimeout .它的作用是立即调用verifyEmptyTeams ,然后将其返回值传递给setTimeout You need to pass just the function to setTimeout instead, so that setTimeout can call it:您只需要将函数传递给setTimeout ,以便setTimeout可以调用它:

setTimeout(verifyEmptyTeams, 864000)

But for longer timeouts like these, it might be more appropriate to use something like node-cron instead.但是对于像这样更长的超时,使用node-cron 之类的东西可能更合适。

cron.schedule('*/864 * * * * *', verifyEmptyTeams);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM