Проверить cron на ошибки

The syntax for the crontab entry looks correct. Indeed, if you edit your crontab using «crontab -e» (as you should), you’ll get an error if you specify a syntactically invalid crontab entry anyway.

  1. Firstly, does /path_to_my_php_script/info.php run correctly from the command-line?

  2. If so, does it also run correctly like this?:

    /bin/sh -c "(export PATH=/usr/bin:/bin; /path_to_my_php_script/info.php </dev/null)"
    
  3. If that works, does it work like this?

    /bin/sh -c "(export PATH=/usr/bin:/bin; /path_to_my_php_script/info.php </dev/null >/dev/null 2>&1)"
    

Step (3) is similar to how cron will run your program (as documented in «man 5 cron».

The most likely problem you’re having is that the PATH cron is using to run your program is too restrictive. Therefore, you may wish to add something like the following to the top of your crontab entry (you’ll need to add in whatever directories your script will need):

PATH=~/bin:/usr/bin/:/bin

Also note that cron will by default use /bin/sh, not bash. If you need bash, also add this to the start of your crontab file:

SHELL=/bin/bash

Note that both those changes will affect all the crontab entries. If you just want to modify these values for your info.php program, you could do something like this:

*/2 * * * * /bin/bash -c ". ~/.bashrc; /path_to_my_php_script/info.php"

It’s also worth mentioning that on a system configured for «mail» (in other words a system which has an MTA configured [sendmail/postfix/etc]), all output from crontab programs is sent to you via email automatically. A default Ubuntu desktop system won’t have local mail configured, but if you’re working on a server you can just type «mail» in a terminal to see all those cron mails. This also applies to the «at» command.

Cron — это демон, который запускает задачи по указанному (заданному) времени и  который работает в наиболее распространенных дистрибутивах Unix / Linux. Поскольку cronjobs основаны на времени, иногда необходимо проверить и убедиться, что задание выполнялось в запланированное время. Иногда люди настраивают cron чтобы они отправляли вывод скрипта через системную почту или перенаправляюте вывод в файл; однако не все кроны настроены одинаково, и мние из них, могут быть настроены на отправку вывода в /dev/null, и тем самым, препятствуя любой возможности проверить выполняемое задание.

Создать cron задание

Первое что стоит проверить — это наличие ПИДа по крону:

# pgrep crond

Или:

# ps ax | grep crond | grep -Ev grep

crond, если он не настроен иначе, будет отправлять сообщение журнала в syslog каждый раз, когда он вызывает запланированное задание. Самый простой способ проверить работу cron на попытку срабатываания задание, — это проверить лог-файл.

В зависимости от Unix/Linux ОС, данный файл может иметь другое название.

Если у вас, CentOS/Fedora/RedHat, то просмотреть нужно:

# less /var/log/cron

Можно отсеять ненужное и поискать только необходимую крон-джобу, например:

# cat /var/log/cron| grep -E "back"

Nov 28 00:00:01 linux-notes CROND[212211]: (root) CMD (/usr/bin/bash /home/linux/scripts/backUPs.sh)
Dec 1 00:00:01 linux-notes CROND[126039]: (root) CMD (/usr/bin/bash /home/linux/scripts/backUPs.sh)

Собственно, все наглядно видно.

Если у вас, Ubuntu/Debian, то просмотреть нужно:

# less /var/log/syslog

Иногда, системные администраторы меняют вывод крона и для того, чтобы проверить куда пишуться логи по cron-job-ам, выполните:

# grep cron /etc/rsyslog.conf

*.info;mail.none;authpriv.none;cron.none                /var/log/messages
# Log cron stuff
cron.*                                                  /var/log/cron

С вывода видно, что у меня используется стандартный файл.

Так же, стоит проверить как настраивали крон-джобы:

# crontab -l

ИЛИ:

# crontab -l -u some_another_user

Возможно было перенаправление вывода в какой-то файл для дальнейшего анализа.

Стоит отметить, то — что некоторые кроны лежат тут:

# ls -lah /etc/cron.daily/
# ls -lah /etc/cron.hourly/
# ls -lah /etc/cron.weekly/
# ls -lah /etc/cron.monthly/

Бывает некоторые задачи запихивают туда.

Чтобы запретить или разрешить добавление крон-задат, нужно прописать юзера в:

# vim /etc/cron.d/cron.allow
# vim /etc/cron.d/cron.deny

Так же, можно восспользоватся следующими командами для проверки статуса, запуска/остановки/перезапуска службы:

# service cron status 
# service cron start 
# service cron stop
# service cron restart

Это все действия были для Linux, но сейчас приведу пример и для mac os x.

Недавно мне пришлось отлаживать работу Cron и проверять, действительно ли она выполняется по заданному расписанию. Я начал искать и проверять все логи и… нашел вроде бы подходящий файл для этого:

# grep cron /var/log/system.log

Но в нем не было признаков логирования крона!

Включить logging для Cron в Mac OSX

Открываем:

# vim /etc/syslog.conf

И прописываем:

cron.* /var/log/cron.log

Для перезапуска syslog-а, выполняем:

# launchctl unload /System/Library/LaunchDaemons/com.apple.syslogd.plist
# launchctl load /System/Library/LaunchDaemons/com.apple.syslogd.plist

Проверяем что получилось!

А для помощи, можно вызвать:

# man crontab

А на этом, у меня все, статья «Проверка работы cron в Unix/Linux» завершена.

cron is a job scheduler for Linux and Unix-like operating systems. It comes pre-installed on all Linux distributions and is most suitable for automating repetitive tasks.

For cron to function properly, you must periodically check that the utility is running fine on your system. You can do that using four different ways, including checking the cron service status, examining cron logs, running a test cron job, and listing down running processes on your system.

What Is cron?

The silent job handler, cron, automates and schedules system tasks. Users who configure and maintain software environments make use of cron to schedule jobs such as commands or shell scripts—also called cron jobs—to run periodically at fixed times or intervals.

cron automates system maintenance or administration tasks that you might need to carry out frequently.

How to Check if cron Is Working on Linux

Here are some of the ways you can check if cron is working properly:

Method 1: Check the cron Service Status on Linux

One way to check whether cron is working is by checking the status of the cron service by running a basic Linux command. Open the Linux terminal by pressing Ctrl + Alt + T and use the systemctl command to check the status of cron:

 sudo systemctl status cron 

If you see the following output, this means cron is active and running fine on your system.

cron status displayed on ubuntu terminal

But what if cron is in an inactive state as shown below?

cron service stopped on ubuntu

You can start the service like this:

 sudo service cron start 

After starting the cron service, enable it so that it starts every time the system reboots:

 sudo service cron enable 

Method 2: Check cron Logs on Linux

Another way to check if cron is working properly is by examining the log files. cron logs are stored in the /var/log/syslog directory on Linux.

syslog is a protocol that Linux systems use to centralize event data logs. Logs are then accessed to perform audits, monitoring, troubleshooting, reporting, and other necessary IT operational tasks.

You can see the cron job logs in the syslog file by executing the following command:

 grep CRON /var/log/syslog 

You will see a similar output indicating that cron is running fine and its logs are being stored in the log file:

cron logs displayed on ubuntu terminal

As the syslog folder contains other system logs along with the cron logs, it can be a little tricky to examine only the cron-related logs in the file. You can resolve this by creating a separate log file that only stores cron entries that appear in the syslog file.

To do that, open the following file using the nano editor:

 nano /etc/rsyslog.d/50-default.conf 

Locate the line that starts with:

 #cron.* 

Uncomment this line by removing the hash (#) sign. Then, save and exit the file by pressing Ctrl + X, then press Y and hit Enter.

Restart the rsyslog service by issuing this command:

 sudo service rsyslog restart 

You will now receive logs in the cron.log file located in the /var/log directory.

If your terminal fails to fetch any logs, that could mean cron is not running. In that case, confirm if cron is working or not using other methods.

Method 3: Running a cron Job on Linux

You can also check if cron is working by simply creating a test cron job and executing it. If the job succeeds in performing the task, this means it’s functioning fine.

You first need to create a Bash script. Bash scripting allows you to automate everyday tasks on Linux.

Let’s create a Bash script that will print “my cronjob is working!” into a TXT file. To create the file, first, find out your present working directory using this command:

 pwd 

Create a file in the current directory using the touch command:

 touch file.txt 

After this, create a Bash file using nano:

 nano script.sh 

Add the following contents to the file:

 #! /usr/bin/bash
echo "my cronjob is working!" >> /home/username/file.txt
bash.sh script created for cronjob

Make sure to provide the correct location of the text file that you created. Save and exit the file by pressing Ctrl + X, then Y, and hit Enter.

Give execute permissions to the Bash script:

 chmod +x script.sh 

Now create a cron job to execute the script. To do that, open the crontab file with:

 crontab -e 

Enter the following line at the end of the file.

 * * * * * /path/to/script.sh 

The five asterisks match the time of execution, in which the first asterisk represents the minutes, the second one represents hours, the third asterisk means the day, the fourth one indicates the month, and the last asterisk indicates the year.

The name of the executable file and its path is also mentioned in the file.

After saving and closing the file, you will see a “crontab: installing new crontab” message on the terminal.

To check if the cron job worked or not, go to the directory of file.txt and print its contents on the terminal using cat:

 cat file.txt 
ubuntu terminal displaying contents of a text file

This indicates that cron is working fine.

Method 4: Check Running Processes on Linux

Another way you can check if the cron daemon is working is by listing down the running processes on your system. You can achieve this using the ps command. The cron daemon will show up in the output as crond.

 ps -ef | grep crond 
ubuntu terminal showing crond process is running

This confirms that the cron process is running on your Linux system.

Automate and Schedule System Tasks With cron

cron is one of the most vital utilities on Linux that allows the system to perform efficiently. Sometimes you have to check whether cron is working while troubleshooting system issues.

You can achieve this by either checking cron logs or seeing the running processes on your system. You can also check the cron status using the systemctl utility. Besides that, running a test cron job can also tell you if the service is running or not.

The smooth working of cron allows you to automate and schedule everyday system jobs. Most of the cron jobs are automatically created by installed applications. Automating and scheduling tasks improves the overall system performance and keeps it healthy.

Sunday, July 3, 2011 — 16:13

Here you can find some simple tests that would confirm the smooth functionality of your crontab.

Test if cron is running

Type the following command:

ps ax | grep cron 

Make sure that cron shows up. Expected output should be something like

[konordo@konordoserv]# ps ax | grep cron
1185 pts/1    S+     0:00 grep cron
1771 ?        Ss     0:00 crond

Test if cron is working

Add the following entry to your crontab. To do so, enter the command

crontab -e

And then add:

* * * * * /bin/echo "foobar" >> /your-path/your-file-name.txt 

After a minute, a file should be created under the specified path, holding the «foobar» content. If you can see the file, congrats, cron is working fine.

Test if your command is working

Add the following to your crontab:

* * * * * /bin/foobar > /your-path/your-file-name.txt 2>&1

and check for errors in look for errors in your-file-name.txt

Test for cron errors — the cron log

You can always check the cron log for errors. The usual location for that would be:

/var/log/cron

or

/var/log/messages

/var/log/cron.log or /var/log/messages for errors

Tags: 

Server configuration, CentOS

We provide the most Shiny Drupal Bits & Pixels

Since Drupal 4.x

Logs probably go to syslog, which varies depending on what syslog daemon is involved and how that is configured to log, start with

grep -r cron /etc/*syslog*

to find where and what is going on on the system, or per derobert under systemd the relevant command is

journalctl -b 0 _SYSTEMD_UNIT=cron.service

Adding a test cron job that touches a file (ideally not in /tmp, unless the vendor makes that per-user private, for security reasons) should also confirm whether cron is working or not, just be sure to eventually remove the test cron job before it fills up a partition or something silly.

Other usability and security pointers: some cron daemons can run scripts directly, in which case you can just copy the script into /etc/cron.daily, though this may not suit something that you do not want to run (with everything else!) at exactly the top of the hour. root running a script under a user’s home directory could be very bad, as a compromise of that user account could then be leveraged to root access, or the script could needlessly fail if the home directory is on NFS or encrypted; move the script elsewhere to avoid this (/root/bin, or somewhere under /usr/local or /opt depending on the local filesystem preferences).

Even more pointers fall into the realm of shell script debugging, mostly to note that cron is not the shell; use env or set to see what is set under cron, check that PATH is correct, and etc. (One old and horrible linux kernel bug involved java daemons crashing but only if they were run from cron; that was fun to debug…)

Понравилась статья? Поделить с друзьями:
  • Проблемы и ошибки семейного воспитания
  • Проверил флешку на наличие ошибок пропали файлы
  • Проверив расчеты нами была найдена ошибка исправьте ошибки
  • Проблемы устранения причин возникновения экспертных ошибок
  • Проверенные текста на ошибки