【问题标题】:node-cron not executing script on interval only console.lognode-cron 仅在间隔时不执行脚本 console.log
【发布时间】:2018-10-07 14:12:50
【问题描述】:

在初始运行时,它会运行 app.js,但是会在间隔时跳过它。我在这里可能做错了什么?

var cron = require('node-cron');

cron.schedule('*/10 * * * * *', function(){
    var shell = require('./app.js');
     commandList = [
        "node app.js"
        ]

        console.log('Bot successfully executed'); 

});

日志:

ec2-user:~/environment $ node forever.js
Bot successfully executed
You have already retweeted this Tweet.
You have already retweeted this Tweet.
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed

【问题讨论】:

    标签: javascript node.js bots node-cron


    【解决方案1】:

    我猜你的app.js 会立即执行代码,所以它只通过要求它来执行(并且要求被缓存,所以它只执行一次)。

    您应该从您的app.js 返回函数,并在每次运行时调用它。

    // app.js
    module.exports = () => { 
        // your original code here
    };
    
    // forever.js
    var cron = require('node-cron');
    var shell = require('./app.js');
    
    cron.schedule('*/10 * * * * *', function(){
        shell();
    
        console.log('Bot successfully executed');
    });
    

    或者你可以在运行前清除require缓存:

    delete require.cache[require.resolve('./app.js')]

    【讨论】:

    • 成功了。是什么最终让这行得通?我尝试了一个没有运气的简单回报。
    • 你的意思是return 来自app.js,没有module.exports 部分?
    • 这个解决方案很有效,因为您在需要 app.js 时返回一个函数,而不是执行代码。然后您可以多次调用该函数。 module.exports 部分是节点模块的工作方式(您分配给它的内容将被导出 = 从 require() 调用返回)
    • 哦,我明白你在说什么。谢谢您的帮助!我坐在这里打了 45 分钟,应该早点问。
    猜你喜欢
    • 2011-05-28
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2015-05-15
    • 2018-02-13
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多