Проверка crontab на ошибки

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 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.

The cron scheduler has been bundled with Unix and Linux operating systems for decades. It’s widely used, and usually very reliable. However, when something goes wrong with cron, it can be difficult to debug.

This guide will walk you through locating cron jobs on your server, validating their schedules, and debugging common runtime problems.

Why cron jobs fail

Cron jobs can fail for a variety of reasons, but at Cronitor we have observed common failure patterns that can provide a useful starting point for your debugging process. In the rest of this guide, we will dive into these common failures with suggestions and solutions.

If you’re adding a new cron job and it is not working…

  • Schedule errors are easy to make

    Cron job schedule expressions are quirky and difficult to write. If your job didn’t run when you expected it to, the easiest thing to rule out is a mistake with the cron expression.

  • Cron has subtle environment differences

    A common experience is to have a job that works flawlessly when run at the command line but fails whenever it’s run by cron. When this happens, eliminate these common failures:

    1. The command has an unresovable relative path like ../scripts. (Try an absolute path)
    2. The job uses environment variables. (Cron does not load .bashrc and similar files)
    3. The command uses advanced bash features (cron uses /bin/sh by default)

    Tip:Our free software, CronitorCLI, includes a shell command to test run any job the way cron does.

  • There is a problem with permissions

    Invalid permissions can cause your cron jobs to fail in at least 3 ways. This guide will cover them all.

If your cron job stopped working suddenly…

  • System resources have been depleted

    The most stable cron job is no match for a disk that is full or an OS that can’t spawn new threads. Check all the usual graphs to rule this out.

  • You’ve reached an inflection point

    Cron jobs are often used for batch processing and other data-intensive tasks that can reveal the constraints of your stack. Jobs often work fine until your data size grows to a point where queries start timing-out or file transfers are too slow.

  • Infrastructure drift occurs

    When app configuration and code changes are deployed it can be easy to overlook the cron jobs on each server. This causes infrastructure drift where hosts are retired or credentials change that break the forgotten cron jobs.

  • Jobs have begun to overlap themselves

    Cron is a very simple scheduler that starts a job at the scheduled time, even if the previous invocation is still running. A small slow-down can lead to a pile-up of overlapped jobs sucking up available resources.

  • A bug has been introduced

    Sometimes a failure has nothing to do with cron. It can be difficult to thoroughly test cron jobs in a development environment and a bug might exist only in production.

How to fix a cron job not running on schedule

You may find that you have scheduled a cron job that is just not running when expected. Follow these steps to locate your scheduled job and diagnose the problem.

1. Locate the scheduled job

Tip: If you know where your job is scheduled, skip this step

Cron jobs are run by a system daemon called crond that watches several locations for scheduled jobs. The first step to understanding why your job didn’t start when expected is to find where your job is scheduled.

Search manually for cron jobs on your server

  • Check your user crontab with crontab -l
    dev01: ~ $ crontab -l
    # Edit this file to introduce tasks to be run by cron.
    # m h  dom mon dow   command
    5 4 \* \* \*      /var/cronitor/bin/database-backup.sh
    
  • Jobs are commonly created by adding a crontab file in /etc/cron.d/
  • System-level cron jobs can also be added as a line in /etc/crontab
  • Sometimes for easy scheduling, jobs are added to /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/ or /etc/cron.monthly/
  • It’s possible that the job was created in the crontab of another user. Go through each user’s crontab using crontab -u username -l

Or, scan for cron jobs automatically with CronitorCLI

  • Install CronitorCLI for free

    Step 1 of 2: Enter your email address for your free CronitorCLI download:

    Download CronitorCLI

    Step 2 of 2: Download CronitorCLI directly from your server:
    • Linux
    • MacOS

    Paste each instruction into a terminal and execute.

    wget https://cronitor.io/dl/linux_amd64.tar.gz
    sudo tar xvf linux\_amd64.tar.gz -C /usr/local/bin/
    sudo cronitor configure --api-key {{ api\_key }} #optional
    

    Paste each instruction into a terminal and execute.

    curl -sOL https://cronitor.io/dl/darwin_amd64.tar.gz
    sudo tar xvf darwin\_amd64.tar.gz -C /usr/local/bin
    sudo cronitor configure --api-key {{ api\_key }} #optional
    
  • Run cronitor list to scan your system for cron jobs:

If you can’t find your job but believe it was previously scheduled double check that you are on the correct server.

2. Validate your job schedule

Once you have found your job, verify that it’s scheduled correctly. Cron schedules are commonly used because they are expressive and powerful, but like regular expressions can sometimes be difficult to read. We suggest using Crontab Guru to validate your schedule.

* Paste the schedule expression from your crontab into the text field on Crontab Guru * Verify that the plaintext translation of your schedule is correct, and that the next scheduled execution times match your expectations * Check that the effective server timezone matches your expectation. In addition to checking system time using date, check your crontab file for TZ or CRON_TZ timezone declarations that would override system settings. For example, CRON_TZ=America/New_York

3. Check your permissions

Invalid permissions can cause your cron jobs to fail in at least 3 ways:

1. Jobs added as files in a /etc/cron.*/ directory must be owned by root. Files owned by other users will be ignored and you may see a message similar to WRONG FILE OWNER in your syslog. 2. The command must be executable by the user that cron is running your job as. For example if your ubuntu user crontab invokes a script like database-backup.sh, ubuntu must have permission to execute the script. The most direct way is to ensure that the ubuntu user owns the file and then ensure execute permissions are available using chmod +x database-backup.sh. 3. The user account must be allowed to use cron. First, if a /etc/cron.allow file exists, the user must be listed. Separately, the user cannot be in a /etc/cron.deny list.

Related to the permissions problem, ensure that if your command string contains a % that it is escaped with a backslash.

4. Check that your cron job is running by finding the attempted execution in syslog

When cron attempts to run a command, it logs it in syslog. By grepping syslog for the name of the command you found in a crontab file you can validate that your job is scheduled correctly and cron is running.

  • Begin by grepping for the command in /var/log/syslog (You will probably need root or sudo access.)
    dev01: ~ $ grep database-backup.sh /var/log/syslog
    Aug  5 4:05:01 dev01 CRON\[2128\]: (ubuntu) CMD (/var/cronitor/bin/database-backup.sh)
    
  • If you can’t find your command in the syslog it could be that the log has been rotated or cleared since your job ran. If possible, rule that out by updating the job to run every minute by changing its schedule to * * * * *.
  • If your command doesn’t appear as an entry in syslog within 2 minutes the problem could be with the underlying cron daemon known as crond. Rule this out quickly by verifying that cron is running by looking up its process ID. If cron is not running no process ID will be returned.
    dev01: ~ $ pgrep cron
    323
    
  • If you’ve located your job in a crontab file but persistently cannot find it referenced in syslog, double check that crond has correctly loaded your crontab file. The easiest way to do this is to force a reparse of your crontab by running EDITOR=true crontab -e from your command prompt. If everything is up to date you will see a message like No modification made. Any other message indicates that your crontab file was not reloaded after a previous update but has now been updated. This will also ensure that your crontab file is free of syntax errors.

If you can see in syslog that your job was scheduled and attempted to run correctly but still did not produce the expected result you can assume there is a problem with the command you are trying to run.

How to debug unexpected cron job failures

Your cron jobs, like every other part of your system, will eventually fail. This section will walk you through testing your job and spotting common failures.

1. Test run your command like cron does

When cron runs your command the environment is different from your normal command prompt in subtle but important ways. The first step to troubleshooting is to simulate the cron environment and run your command in an interactive shell.

Run any command like cron does with CronitorCLI

  • Install CronitorCLI for free

    Step 1 of 2: Enter your email address for your free CronitorCLI download:

    Download CronitorCLI

    Step 2 of 2: Download CronitorCLI directly from your server:
    • Linux
    • MacOS

    Paste each instruction into a terminal and execute.

    wget https://cronitor.io/dl/linux_amd64.tar.gz
    sudo tar xvf linux\_amd64.tar.gz -C /usr/local/bin/
    sudo cronitor configure --api-key {{ api\_key }} #optional
    

    Paste each instruction into a terminal and execute.

    curl -sOL https://cronitor.io/dl/darwin_amd64.tar.gz
    sudo tar xvf darwin\_amd64.tar.gz -C /usr/local/bin
    sudo cronitor configure --api-key {{ api\_key }} #optional
    
  • To force a scheduled cron job to run immediately, use cronitor select to scan your system and present a list of jobs to choose from.

  • To simulate running any command the way cron does, use cronitor shell:

Or, manually test run a command like cron does

  • If you are parsing a file in /etc/cron.d/ or /etc/crontab each line is allowed to have an effective «run as» username after the schedule and before the command itself. If this applies to your job, or if your job is in another user’s crontab, begin by opening a bash prompt as that user sudo -u username bash
  • By default, cron will run your command using /bin/sh, not the bash or zsh prompt you are familiar with. Double check your crontab file for an optional SHELL=/bin/bash declaration. If using the default /bin/sh shell, certain features that work in bash like [[command]] syntax will cause syntax errors under cron.
  • Unlike your interactive shell, cron doesn’t load your bashrc or bash_profile so any environment variables defined there are unavailable in your cron jobs. This is true even if you have a SHELL=/bin/bash declaration. To simulate this, create a command prompt with a clean environment.
    dev01: ~ $ env -i /bin/sh
    
  • By default, cron will run commands with your home directory as the current working directory. To ensure you are running the command like cron does, run cd ~ at your prompt.
  • Paste the command to run (everything after the schedule or declared username) into the command prompt. If crontab is unable to run your command, this should fail too and will hopefully contain a useful error message. Common errors include invalid permissions, command not found, and command line syntax errors.
  • If no useful error message is available, double check any application logs your job is expected to produce, and ensure that you are not redirecting log and error messages. In linux, command >> /path/to/file will redirect console log messages to the specified file and command >> /path/to/file 2>&1 will redirect both the console log and error messages. Determine if your command has a verbose output or debug log flag that can be added to see additional details at runtime.
  • Ideally, if your job is failing under cron it will fail here too and you will see a useful error message, giving you a chance to modify and debug as needed. Common errors include file not found, misconfigured permissions, and commandline syntax errors.

2. Check for overlapping jobs

At Cronitor our data shows that runtime durations increase over time for a large percentage of cron jobs. As your dataset and user base grows it’s normal to find yourself in a situation where cron starts an instance of your job before the previous one has finished. Depending on the nature of your job this might not be a problem, but several undesired side effects are possible:

  • Unexpected server or database load could impact other users

  • Locking of shared resources could cause deadlocks and prevent your jobs from ever completing successfully

  • Creation of an unanticipated race condition that might result in records being processed multiple times, amplifying server load and possibly impacting customers

    To verify if any instances of a job are running on your server presently, grep your process list. In this example, 3 job invocations are running simultaneously:

    dev01: ~ $ ps aux | grep database-backup.sh
    ubuntu           1343   0.0  0.1  2585948  12004   ??  S    31Jul18   1:04.15 /var/cronitor/bin/database-backup.sh
    ubuntu           3659   0.0  0.1  2544664    952   ??  S     1Aug18   0:34.35 /var/cronitor/bin/database-backup.sh
    ubuntu           7309   0.0  0.1  2544664   8012   ??  S     2Aug18   0:18.01 /var/cronitor/bin/database-backup.sh
    

To quickly recover from this, first kill the overlapping jobs and then watch closely when your command is next scheduled to run. It’s possible that a one time failure cascaded into several overlapping instances. If it becomes clear that the job often takes longer than the interval between job invocations you may need to take additional steps, e.g.:

  • Increase the duration between invocations of your job. For example if your job runs every minute now, consider running it every other minute.
  • Use a tool like flock to ensure that only a single instance of your command is running at any given time. Using flock is easy. After installing from apt-get or yum you only need to prefix the command in your crontab:
    dev01: ~ $ crontab -l
    # Edit this file to introduce tasks to be run by cron.
    # m h  dom mon dow   command
    \* \* \* \* \*      flock -w 0 /var/cronitor/bin/database-backup.sh
    

Read more about flock from the man page.

What to do if nothing else works

Here are a few things you can try if you’ve followed this guide and find that your job works flawlessly when run from the cron-like command prompt but fails to complete successful under crontab.

  • First get the most basic cron job working with a command like date >> /tmp/cronlog. This command will simply echo the execution time to the log file each time it runs. Schedule this to run every minute and tail the logfile for results.

  • If your basic command works, replace it with your command. As a sanity check, verify if it works.

  • If your command works by invoking a runtime like python some-command.py perform a few checks to determine that the runtime version and environment is correct. Each language runtime has quirks that can cause unexpected behavior under crontab.

    • For python you might find that your web app is using a virtual environment you need to invoke in your crontab.
    • For node a common problem is falling back to a much older version bundled with the distribution.
    • When using php you might run into the issue that custom settings or extensions that work in your web app are not working under cron or commandline because a different php.ini is loaded.

    If you are using a runtime to invoke your command double check that it’s pointing to the expected version from within the cron environment.

  • If nothing else works, restart the cron daemon and hope it helps, stranger things have happened. The way to do this varies from distro to distro so it’s best to ask google.


Я хочу проверить, работает ли определенный crontab правильно. Я добавил работу, как это:

  */2 * * * * /path_to_my_php_script/info.php >/dev/null 2>&1

Я знаю, что перенаправляю на нулевое устройство, но не уверен, что приведенная выше команда хороша.

* Редактировать 1: В моем / var / log / syslog каждые две минуты у меня появляется следующая ошибка:

 (CRON) error (grandchild #2788 failed with exit status 2)

* Редактировать 2: Нет ошибок в журналах с этим новым заданием:

 */2 * * * * /usr/bin/php /path_to_my_php_script/info.php >/dev/null 2>&1


Ответы:


Синтаксис для записи в crontab выглядит правильно. Действительно, если вы отредактируете свой crontab, используя « crontab -e» (как и должно быть), вы получите ошибку, если в любом случае укажете синтаксически неверную запись в crontab.

  1. Во-первых, /path_to_my_php_script/info.phpправильно ли работает из командной строки?

  2. Если так, это также работает правильно, как это ?:

    /bin/sh -c "(export PATH=/usr/bin:/bin; /path_to_my_php_script/info.php </dev/null)"
    
  3. Если это работает, это работает так?

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

Шаг (3) аналогичен тому, как cron будет запускать вашу программу (как описано в «man 5 cron»).

Наиболее вероятная проблема, с которой вы сталкиваетесь, заключается в том, что cron PATH использует для запуска вашей программы слишком строгие ограничения. Поэтому вы можете добавить что-то вроде следующего в начало вашей записи crontab (вам нужно будет добавить в любые каталоги, которые понадобятся вашему скрипту):

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

Также обратите внимание, что по умолчанию будет использоваться cron /bin/sh, а не bash. Если вам нужен bash, также добавьте это в начало вашего файла crontab:

SHELL=/bin/bash

Обратите внимание, что оба эти изменения затронут все записи в crontab. Если вы просто хотите изменить эти значения для вашей info.phpпрограммы, вы можете сделать что-то вроде этого:

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

Также стоит упомянуть, что в системе, настроенной на «почту» (другими словами, в системе, в которой настроен MTA [sendmail / postfix / etc]), весь вывод из программ crontab отправляется вам по электронной почте автоматически. В стандартной настольной системе Ubuntu локальная почта не будет настроена, но если вы работаете на сервере, вы можете просто набрать «mail» в терминале, чтобы увидеть все эти cron-сообщения. Это также относится к команде » at«.




Хотя очень редко, иногда Cron перестает работать должным образом, даже если служба работает. Вот как проверить, что crond работает и остановить / запустить службу.

В Linux:

service crond status
service crond stop
service crond start

В Ubuntu и других системах на основе Debian:

service cron status
service cron stop
service cron start



Не перенаправляйте вывод ошибок в / dev / null и grep / var / log / syslog для вывода cron.

grep cron /var/log/syslog

Вы можете сразу же показать ошибки при сохранении файла после редактирования /etc/crontabили файлов внутри /etc/cron.d/с помощью:

tail -f /var/log/syslog | grep --line-buffered cron

Если редактирование в порядке, вы увидите только RELOADуведомление, ошибки будут появляться как

Jul 9 09:39:01 vm cron[1129]: Error: bad day-of-month; while reading /etc/cron.d/new 


Вы можете увидеть свой активный cron с помощью команды терминала:

crontab -l

Вот параметры по порядку:

  1. мин (0 — 59)

  2. час (0 — 23)

  3. день месяца (1 — 31)

  4. месяц (1 — 12)

  5. день недели (0 — 6) (воскресенье = 0)

  6. команда

Итак, вы вызываете свой сценарий каждую первую минуту каждого часа. Вы должны проверять свои результаты с более частым интервалом для целей тестирования:

* * * * * <command> #Runs every minute

Это будет называть это каждую минуту!



Для временной части в каждой строке вы можете использовать этот тестер cron для проверки / проверки вашего определения времени cron.




Я считаю, что вы также можете использовать run-partsдля запуска заданий cron вне группы. Это именно то, что cron использует для запуска периодических заданий cron, поэтому, предоставляя соответствующие аргументы, вы можете запускать их в любое время.

Если вы просто хотите запустить один файл вместо всех заданий cron, определенных, например, /etc/cron.dailyвам нужно будет указать аргумент regex вместе с действительным regex.run-parts --list --regex '^p.*d$' /etc

Имейте в виду, что задания cron обычно называются без расширения и помечаются как исполняемые, поэтому убедитесь, что ваши сценарии похожи, хотя использование регулярного выражения может позволить вам запустить сценарий с расширением.


ах !!

получил ответ сам, проверил и не нашел crondвнутри директории установки по умолчанию т.е./etc/init.d/

сейчас попробую ответить.

примечание — я проверить cron.allow, cron.denyтоже. Пока все хорошо.

Crontab — чрезвычайно полезный планировщик заданий в системах на базе Linux, который позволяет вам преобразовывать повседневные рутинные задачи в задания crontab, которые могут запускаться автоматически по заданному расписанию. Однако, поскольку этот планировщик заданий работает в фоновом режиме, большинство пользователей задаются вопросом, работает он или нет.

Иногда вы назначаете задачи резервного копирования вашей системы или обновления ее планировщику заданий crontab. Эти задачи считаются очень важными для нормальной работы любой компьютерной системы. Вот почему, если они будут пропущены по какой-либо причине, ваша система, соответственно, перестанет работать. Таким образом, считается чрезвычайно важным следить за своим планировщиком заданий crontab, а также быть в курсе того, работает он или нет, и выполняет ли назначенные ему задания или нет.

Вот почему цель сегодняшней статьи — научить вас двум методам проверки работы crontab при использовании Linux Mint 20.

Способы проверки работы Crontab

Следующие два метода можно использовать, чтобы проверить, работает ли crontab. Первый метод является простым, тогда как второй метод немного сложнее, так как в нем больше шагов, чем в первом. Во всяком случае, мы собираемся изложить оба метода ниже:

Метод №1: Проверяя статус службы Cron

Чтобы проверить, работает ли crontab, посмотрев статус службы Cron, вам необходимо выполнить следующие шаги:

Запустите терминал в любом дистрибутиве Linux, с которым вы работаете. Как уже было сказано выше, мы использовали Linux Mint 20, чтобы продемонстрировать оба метода проверки, работает ли crontab или нет. Поэтому мы также показали терминал этого дистрибутива Linux на изображении ниже:

Теперь для проверки статуса службы Cron в Linux Mint 20 вам необходимо ввести следующую команду:

$ systemctl status cron

Выполнение команды «systemctl» вместе с флагом статуса проверит статус службы Cron, как показано на изображении ниже. Если статус «Активен (Выполняется)», то будет подтверждено, что crontab работает отлично, в противном случае — нет.

В нашем случае crontab работал нормально, поэтому вы можете увидеть статус «Активен (работает)» на изображении, показанном выше. Однако, если ваш crontab не работает, вы всегда можете запустить эту службу, выполнив следующую команду в своем терминале:

$ sudo service cron start

Для запуска новой службы в Linux Mint 20 всегда требуются права пользователя root. Вот почему, если вы забудете упомянуть ключевое слово «sudo» перед вышеупомянутой командой, на терминале появится сообщение об ошибке. Однако, если вы вошли в систему под учетной записью пользователя root, вы можете обойтись даже без ключевого слова «sudo».

Метод № 2: Запуск задания Crontab

Чтобы проверить, работает ли crontab или нет, запустив задание crontab, вам необходимо выполнить следующие шаги:

В этом методе мы сначала создадим сценарий bash, который мы будем запускать как задание crontab. Если наша работа crontab будет работать, я.е. если наш сценарий bash будет выполняться так, как задумано, это будет означать, что crontab работает отлично, в противном случае не. Итак, мы решили создать bash-файл в нашем домашнем каталоге с именем Cron.ш. После создания этого файла мы открыли его и набрали сценарий, показанный на изображении ниже, в нашем файле bash. Этот скрипт просто выводит фиктивное сообщение на терминал. Затем мы сохранили наш файл bash и закрыли его.

Следующий шаг — сделать наш файл bash исполняемым, чтобы у нашего задания crontab были права на выполнение этого файла bash. Чтобы сделать наш только что созданный скрипт bash исполняемым, мы запустим следующую команду в нашем терминале:

$ chmod + x Cron.ш

Выполнение этой команды не отобразит никаких выходных данных на терминале, скорее управление будет передано вам, что укажет на то, что эта команда была выполнена успешно.

Теперь мы создадим задание crontab для запуска этого файла bash. Для этого нам нужно открыть файл crontab на терминале, выполнив в нем команду, указанную ниже:

$ crontab -e

Когда файл crontab появится на вашем терминале, вам нужно будет ввести строку, выделенную на следующем изображении, в вашем файле. Ввод этой строки создаст задание crontab для выполнения нашего файла bash каждую секунду. Мы нажали Ctrl + X, чтобы сохранить файл crontab и закрыть его, чтобы продолжить.

Как только этот файл закроется, демон Cron установит новый crontab, как показано на изображении ниже, поскольку мы только что изменили файл crontab.

Если наш crontab будет работать нормально, то наш bash-скрипт будет выполняться каждую секунду. Чтобы убедиться в этом, нам нужно проверить файл / var / log / syslog, выполнив следующую команду в терминале:

$ sudo grep -a «Крон.sh ”/ var / log / syslog

Этот файл будет содержать журнал всех случаев выполнения вашего файла bash, что будет означать, что ваш crontab работает, как показано на изображении ниже:

Заключение

В сегодняшней статье мы научили вас двум методам проверки того, работает ли crontab или нет. Первого метода должно быть вполне достаточно для вас, если вы намереваетесь только проверить статус своей службы crontab, однако, если вы хотите узнать, успешно ли выполняется какое-либо конкретное задание crontab, тогда вам придется выполнить метод № 2. Эти методы были выполнены в Linux Mint 20, однако вы также можете использовать любой другой предпочтительный дистрибутив Linux.

Понравилась статья? Поделить с друзьями:
  • Проверить фразу на ошибки
  • Проверка ccd на ошибки
  • Проверить флешку на вирусы и ошибки
  • Проверка btrfs на ошибки
  • Проверить флешку transcend на ошибки