为什么 cron 不会执行我的 node.js 脚本? [英] Why won't cron execute my node.js script?
问题描述
我希望我的服务器每分钟执行一个节点脚本.如果我手动执行文件 (./main.js
),程序会完美执行,所以我很确定这不是问题.但是当我将它交给 cron 执行时,什么也没有发生.
I want my server to execute a node script every minute. The program executes perfectly if I execute the file manually (./main.js
), so I'm pretty sure it's not the problem. But when I hand it over to cron to execute, nothing happens.
这是 cron 文件中的一行.
Here's the line from the cron file.
*/1 * * * */home/bryce/scripts/wudu/main.js
这是一个示例日志:
Oct 11 15:21:01 server CROND[2564]: (root) CMD (/home/bryce/scripts/wudu/main.js)
可执行文件:home/bryce/scripts/wudu/main.js
#!/usr/bin/env node
var program = require('commander');
var v = require('./cli/validation');
var a = require('./cli/actions');
program
.version('0.0.1')
.option('-u, --url', 'Register url')
.option('-s, --selector', 'Register selector')
.option('-p, --pagination', 'Register pagination')
.option('-i, --index', 'Pass an index, to destroy')
.parse(process.argv);
var args = process.argv.slice(2),
mode = v.mode(args[0]),
options = v.hasArgs(mode, program);
a.init(mode, options);
知道为什么我的无线电静音了吗?我应该在其他地方调试吗?
Any idea why I'm getting radio silence? Somewhere else I should be looking to debug?
更新:
我相信问题与我的相对文件路径有关,并且 main.js 是从它自己的目录之外执行的.
I believe the problem has to do with my relative filepaths, and main.js being executed from outside its own directory.
现在,我已经将 exe.sh
放在 wudu
目录中.它看起来像这样:
So now, I've placed exe.sh
in the wudu
directory. It looks like this:
#!/bin/bash
cd ${0%/*}
./main.js mail
exit
现在,我已将 cron 设置为每分钟执行一次此文件.我尝试从其他文件夹执行此文件,它按预期工作.但是,cron 并没有发现它.
Now, I've set cron to execute this file every minute. I tried executing this file from other folders, and it works as expected. But again, cron isn't picking it up.
推荐答案
将执行包装在一个 shell 脚本中,很可能该脚本在 cron 中的执行与从命令行运行时的环境设置不同.
Wrapping the execution in a shell script, it's likely the execution of the script in cron doesn't have the same environment set as when you run from the command line.
尝试通过设置 NODE_PATH
& 在 cron 中预先执行 shell 脚本<代码>路径代码>
(如果您需要这些值,请在命令行输入:echo $NODE_PATH
和 echo $PATH
)
Try prefacing the execution of the shell script in cron with setting NODE_PATH
& PATH
(if you need these values, on a command line type: echo $NODE_PATH
and echo $PATH
)
因此,您的 cron 条目将如下所示:
So, your cron entry would look like:
*/1 * * * * NODE_PATH=/usr/local/lib/node_modules PATH=/opt/local/bin:ABC:XYZ /home/bryce/scripts/wudu/exe.sh
只需确保用实际值替换 NODE_PATH
&PATH
包含您从第一次执行的 echo
命令中获得的内容.
Just make sure to substitute the actual values for NODE_PATH
& PATH
with what you get from the echo
commands that you first did.
这篇关于为什么 cron 不会执行我的 node.js 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!