cronjob 不执行独立运行的脚本 [英] cronjob does not execute a script that works fine standalone

查看:36
本文介绍了cronjob 不执行独立运行的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 /var/www/html/dbsync/index.php 中有我的 php 脚本文件.当 cd/var/www/html/dbsync/ 并运行 php index.php 时,它完美运行.

I have my php script file in /var/www/html/dbsync/index.php. When cd /var/www/html/dbsync/ and run php index.php it works perfectly.

我想通过sh文件调用PHP文件,SH文件的位置如下

I want to call PHP file through sh file, the location of SH file is as below

/var/www/html/dbsync/dbsync.sh

这是dbsync.sh文件的内容:

/usr/bin/php /var/www/html/dbsync/index.php >> /var/www/html/dbsync/myscript.log 2>&1 -q -f

当我 cd/var/www/html/dbsync/ 并运行 ./dbsync.sh 时,它也能完美运行.

When I cd /var/www/html/dbsync/ and run ./dbsync.sh it works perfectly as well.

现在,如果我设置 crontab 如下:

Now if I set up crontab as below:

1 * * * * /var/www/html/dbsync/dbsync.sh /var/www/html/dbsync

但是,这个 crontab 没有按预期工作.

However, this crontab is not working as expected.

有什么问题?

推荐答案

如评论中所见,问题在于您没有定义应该使用什么程序来执行脚本.考虑到 cronjob 是在一个很小的环境中执行的;在那里,不能假设太多.这就是我们定义完整路径等的原因.

As seen in comments, the problem is that you are not defining what program should be used to execute the script. Take into account that a cronjob is executed in a tiny environment; there, not much can be assumed. This is why we define full paths, etc.

所以你需要这样说:

1 * * * * /bin/sh /var/www/html/dbsync/dbsync.sh /var/www/html/dbsync
#         ^^^^^^^

/bin/sh 是您要用来执行脚本的二进制文件.

/bin/sh being the binary you want to use to execute the script.

否则,您可以为脚本设置执行权限并添加一个shell-script header 告诉它使用什么解释器:

Otherwise, you can set execution permissions to the script and add a shell-script header telling it what interpreter to use:

#!/bin/sh

如果这样做,则不需要添加二进制文件的路径.

If you do this, adding the path of the binary is not necessary.

来自 解决 cron 作业的常见问题:

使用相对路径.如果您的 cron 作业正在执行某个脚本种类,您必须确保在该脚本中仅使用绝对路径.例如,如果您的脚本位于/path/to/script.phpand你试图在同一目录中打开一个名为 file.php 的文件,您不能使用相对路径,例如 fopen(file.php).该文件必须从其绝对路径调用,如下所示:fopen(/path/to/file.php).这是因为 cron 作业不一定从以下目录运行脚本所在的位置,因此必须专门调用所有路径.

Using relative paths. If your cron job is executing a script of some kind, you must be sure to use only absolute paths inside that script. For example, if your script is located at /path/to/script.phpand you're trying to open a file called file.php in the same directory, you cannot use a relative path such as fopen(file.php). The file must be called from its absolute path, like this: fopen(/path/to/file.php). This is because cron jobs do not necessarily run from the directory in which the script is located, so all paths must be called specifically.

<小时>

另外,我知道您想每分钟运行一次.如果是这样, 1 * * * * 不会做.相反,它会每小时过去的每 1 分钟 运行一次.所以如果你想每分钟运行一次,就说* * * * *.


Also, I understand you want to run this every minute. If so, 1 * * * * won't do. Intead, it will run at every 1st minute past every hour. So if you want to run it every minute, say * * * * *.

这篇关于cronjob 不执行独立运行的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆