【发布时间】:2020-01-21 04:00:09
【问题描述】:
我想在我的 EC2 主机上使用 cron 作业在我的项目文件夹中执行 node.js 脚本。我知道这个问题在这个论坛上已经被问过很多次了,我按照答案到达了我现在的位置,但我很难得到结果。
在我的根目录下有两个文件夹:home 和 usr
我的节点位于 /usr/bin/node(which node 给出了这条路径)
我的节点文件位于 /home/ubuntu/my-crm-app/test.js
test.js 只有一个 console.log("this is a test") - 但如果可行,我稍后会编写更多代码。
现在如果我从任何地方执行/usr/bin/node /home/ubuntu/my-crm-app/test.js,它会打印出日志,
事实上,即使我执行node /home/ubuntu/my-crm-app/test.js,它也会打印出日志。所以这意味着我的节点和项目文件的路径是正确的并且可以工作。
我在系统中输入 crontab -e 并选择 vim basic 作为我的编辑器来编写 cron 作业。它看起来像这样:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
*/1 * * * * /usr/bin/node /home/ubuntu/my-crm-app/test.js
所以我想每分钟执行一次日志。我保存 vim 文件并从中取出并等待等待,但没有任何反应。据我了解,我的 cron 语法是正确的。那么问题似乎是什么?我是否需要在 vim 文件中为 node 和我的 test.js 提供不同的路径语法?
谢谢。
【问题讨论】:
-
您是否尝试过使用绝对路径:/usr/bin/node.
-
是的,我做到了。我使用了 /usr/bin/node 路径,但它仍然不会打印出日志。
-
你可以尝试制作一个脚本并将其添加到cron中。就像创建一个 .sh 文件并在该文件中添加 /usr/bin/node /home/ubuntu/my-crm-app/test.js 一样。然后只需从 cron 调用该脚本。 */5 * * * * /path/to/script.sh
-
好的,会试试的。那么 .sh 文件应该保存在哪里呢?在根目录?还是在我家/ubuntu 里面?在哪里?
-
把它放在你的主目录中,并在调用时给出整个绝对路径。
标签: node.js ubuntu amazon-ec2 vim cron