【问题标题】:Cron does not execute the nodejs scriptcron 不执行 nodejs 脚本
【发布时间】:2019-10-30 15:39:15
【问题描述】:

我想通过 cron 运行我的脚本。但是当我尝试执行它时,脚本没有启动。我做错了什么?

sudo crontab -e:

5 * * * * /home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js

index.js:

#!/usr/bin/env node

...
var fs = require('fs');

function formatDate(date) {
    var monthNames = [
        "January", "February", "March",
        "April", "May", "June", "July",
        "August", "September", "October",
        "November", "December"
    ];
    var day = date.getDate();
    var monthIndex = date.getMonth();
    var year = date.getFullYear();
    return day + '_' + monthNames[monthIndex] + '_' + year;
}

function formatTime(time) {
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return hours + '_' + minutes + '_' + seconds;
}

var ws = fs.createWriteStream(`./log/test-${formatDate(new Date())}-${formatTime(new Date())}.log`, {
    'flags': 'w',
    'encoding': 'utf8'
});

process.stdout.wr = process.stdout.write;
process.stdout.er = process.stderr.write;

process.stdout.write = function (mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.wr(mes, c);
};

process.stderr.write = function (mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.er(mes, c);
};
...

grep CRON /var/log/syslog:

Jun 17 09:05:01 admin-serv CRON[861]: (admin) CMD (/home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js)

ps辅助| grep index.js

admin 921 0.0 0.0 21320 1016 pts/0 S+ 09:05 0:00 grep --color=auto index.js

当然,当我运行这个命令时

/home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js

通过终端,一切正常。

【问题讨论】:

  • 我注意到您没有指定应该由哪个用户运行该命令? linuxconfig.org/linux-crontab-reference-guide
  • @OddmarDam 以管理员身份运行并编辑文件也无济于事。
  • 该文件对运行它的用户来说是可执行的吗?
  • @OddmarDam ls -l -rwxrwxr-x 1 admin admin 3114 jun 17 08:43 index.js
  • 一个不相关的问题,但是为什么节点脚本上有bash shebang?不应该是#!/usr/bin/env node吗?

标签: node.js cron


【解决方案1】:

当您从 cron 执行脚本时,process.stdout 不起作用。如果您打算在没有终端的情况下运行脚本,则需要使用 console.log。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2013-10-11
    • 2019-08-28
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多