如何知道 Crontab 是否在工作?

How to know if Crontab is working?

我正在尝试 运行 一个简单的 crontab(在 mac OSX 终端上)

我的 cronjob 看起来像这样:

* * * * * /Users/tanavya.dimri/Documents/cron.sh

cron.sh:

#!/bin/bash
cd /Users/tanavya.dimri/Documents
python hello.py > empty

而hello.py就是

print "Hello"

当我只是 运行 sh cron.sh 时它起作用了。 Empty 只是一个空的文本文件,确实会更改为 "Hello"。 但是,我真的不知道它是否与 crontab 一起工作,因为在我从中删除 hello 后文件没有改变。

删除文件后再试。如果 crontab 运行,它应该创建它

有一种方法可以检查您的 crontab 作业是否 运行 成功。请注意,cron 命令中的日志文件引用是使用完整路径而不是相对路径给出的。您需要确保您的脚本使用完整路径或 cd 到正确的工作目录。

Crontab Log: How to Log the Output of My Cron Script

Let us say that you’ve added the backup.sh to your crontab as shown below to execute it at midnight every day.

$ crontab -e 59 23 * * * /home/john/bin/backup.sh

To verify whether the this job got executed successfully or not, check the /var/log/cron file, which contains information about all the cron jobs that gets executed in your system. As you see from the following output, john’s cron job got executed succesfully.

$ tail /var/log/cron
Oct  8 22:00:00 dev-db crond[18340]: (root) CMD (/bin/sh /home/root/bin/system_check &)
Oct  8 23:00:00 dev-db crond[20348]: (oracle) CMD (/bin/sh /home/oracle/bin/cleanup.sh &)
Oct  8 23:59:00 dev-db crond[20399]: (john) CMD (/bin/sh /home/john/bin/backup.sh &)

Cron log contains the following information:

Timestamp – The date and time when the cron job was executed

Hostname – The hostname of the server (For example, dev-db)

The cron deamon name and the PID. For example, crond[20399]

Username – The username under which this cron job got executed. For example, john.

CMD – Anything following this is the real command that got executed at that time.

If there are any echo statements inside the backup.sh, you might want to log those into a file. In general, if the backup.sh cron script throws any output (including errors), you might want to log those to a log file. To do this, modify the crontab entry and add the output and error redirection as shown below.

$ crontab -e 59 23 * * * /home/john/bin/backup.sh > /home/john/logs/backup.log 2>&1

In the above:

/home/john/logs/backup.log indicates that the standard output of the backup.sh script will be redirected to the backup.log file.

2>&1 indicates that the standard error (2>) is redirected to the same file descriptor that is pointed by standard output (&1).

So, both standard output and error will be redirected to /home/john/logs/backup.log

首先检查您的 cron.sh 文件是否有足够的权限。

chmod 755 cron.sh

然后将您的 crontab 修改为 运行 定期(即 1 分钟):

 */1 * * * * /Users/tanavya.dimri/Documents/cron.sh

默认情况下 cronjobs 登录 /var/log/syslog

因此,您可以简单地 grep 该日志 CRON 并检查您的作业执行情况:

grep CRON /var/log/syslog