Linux red hat crontab

Chapter 34. Automated Tasks

In Linux, tasks can be configured to run automatically within a specified period of time, on a specified date, or when the system load average is below a specified number. Red Hat Enterprise Linux is pre-configured to run important system tasks to keep the system updated. For example, the slocate database used by the locate command is updated daily. A system administrator can use automated tasks to perform periodic backups, monitor the system, run custom scripts, and more.

34.1. Cron

Cron is a daemon that can be used to schedule the execution of recurring tasks according to a combination of the time, day of the month, month, day of the week, and week.

Cron assumes that the system is on continuously. If the system is not on when a task is scheduled, it is not executed. To schedule one-time tasks, refer to Section 34.2, “At and Batch”.

To use the cron service, the vixie-cron RPM package must be installed and the crond service must be running. To determine if the package is installed, use the rpm -q vixie-cron command. To determine if the service is running, use the command /sbin/service crond status .

34.1.1. Configuring Cron Tasks

SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly

The first four lines are variables used to configure the environment in which the cron tasks are run. The SHELL variable tells the system which shell environment to use (in this example the bash shell), while the PATH variable defines the path used to execute commands. The output of the cron tasks are emailed to the username defined with the MAILTO variable. If the MAILTO variable is defined as an empty string ( MAILTO=»» ), email is not sent. The HOME variable can be used to set the home directory to use when executing commands or scripts.

minute hour day month dayofweek command

dayofweek — any integer from 0 to 7, where 0 or 7 represents Sunday (or the short name of the week such as sun or mon)

command — the command to execute (the command can either be a command such as ls /proc >> /tmp/proc or the command to execute a custom script)

Читайте также:  Astra linux обновить пакеты через терминал

For any of the above values, an asterisk (*) can be used to specify all valid values. For example, an asterisk for the month value means execute the command every month within the constraints of the other values.

A hyphen (-) between integers specifies a range of integers. For example, 1-4 means the integers 1, 2, 3, and 4.

A list of values separated by commas (,) specifies a list. For example, 3, 4, 6, 8 indicates those four specific integers.

The forward slash (/) can be used to specify step values. The value of an integer can be skipped within a range by following the range with /integer> . For example, 0-59/2 can be used to define every other minute in the minute field. Step values can also be used with an asterisk. For instance, the value */3 can be used in the month field to run the task every third month.

As shown in the /etc/crontab file, the run-parts script executes the scripts in the /etc/cron.hourly/ , /etc/cron.daily/ , /etc/cron.weekly/ , and /etc/cron.monthly/ directories on an hourly, daily, weekly, or monthly basis respectively. The files in these directories should be shell scripts.

If a cron task is required to be executed on a schedule other than hourly, daily, weekly, or monthly, it can be added to the /etc/cron.d/ directory. All files in this directory use the same syntax as /etc/crontab . Refer to Example 34.1, “Crontab Examples” for examples.

Example 34.1. Crontab Examples

# record the memory usage of the system every monday # at 3:30AM in the file /tmp/meminfo 30 3 * * mon cat /proc/meminfo >> /tmp/meminfo # run custom script the first day of every month at 4:10AM 10 4 1 * * /root/scripts/backup.sh

Users other than root can configure cron tasks by using the crontab utility. All user-defined crontabs are stored in the /var/spool/cron/ directory and are executed using the usernames of the users that created them. To create a crontab as a user, login as that user and type the command crontab -e to edit the user’s crontab using the editor specified by the VISUAL or EDITOR environment variable. The file uses the same format as /etc/crontab . When the changes to the crontab are saved, the crontab is stored according to username and written to the file /var/spool/cron/username .

The cron daemon checks the /etc/crontab file, the /etc/cron.d/ directory, and the /var/spool/cron/ directory every minute for any changes. If any changes are found, they are loaded into memory. Thus, the daemon does not need to be restarted if a crontab file is changed.

Читайте также:  Linux чем открыть conf

34.1.2. Controlling Access to Cron

The /etc/cron.allow and /etc/cron.deny files are used to restrict access to cron. The format of both access control files is one username on each line. Whitespace is not permitted in either file. The cron daemon ( crond ) does not have to be restarted if the access control files are modified. The access control files are read each time a user tries to add or delete a cron task.

If the file cron.allow exists, only users listed in it are allowed to use cron, and the cron.deny file is ignored.

34.1.3. Starting and Stopping the Service

To start the cron service, use the command /sbin/service crond start . To stop the service, use the command /sbin/service crond stop . It is recommended that you start the service at boot time. Refer to Chapter 19, Controlling Access to Services for details on starting the cron service automatically at boot time.

Источник

Настройка задач Cron

Основной файл конфигурации cron, /etc/crontab , содержит следующие строки:

SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly

Первые четыре строки — это переменные, настраивающие среду окружения, в котором будут работать задачи cron. Значение переменной SHELL сообщает системе о том, какую оболочку использовать (в этом примере будет использована оболочка bash), а переменная PATH определяет пути, используемые для выполнения команд. Результат выполнения задач cron будет выслан по электронной почте пользователю, определённому в переменной MAILTO . Если в качестве значения переменной MAILTO задана пустая строка ( MAILTO=»» ), электронные письма отправляться не будут. Переменная HOME задаёт домашний каталог, используемый при выполнения команд или сценариев.

Каждая строка в файле /etc/crontab имеет следующий формат:

minute hour day month dayofweek command

minute — любое целое число от 0 до 59

hour — любое целое от 0 до 23

day — любое целое от 1 до 31 (день должен быть корректным, если указан месяц)

month — любое целое от 1 до 12 (или короткое название месяца, например: jan, feb и так далее)

dayofweek — любое целое от 0 до 7, где 0 или 7 означает Воскресенье (или короткое название дня недели, например: sun, mon и так далее)

command — команда, которая должны быть выполнена. Командой может быть как простая команда, например, ls /proc >> /tmp/proc , или команда запуска написанного вами специального сценария.

Для любых указанных выше параметров можно использовать звездочку (*), что означает все допустимые значения. Например, если поставить звёздочку в значении месяца, команда будет выполняться каждый месяц во время, указанное другими параметрами.

Читайте также:  Finding java classpath linux

Дефис (-) между целыми числами обозначает диапазон чисел. Например, 1-4 означает целые числа 1, 2, 3 и 4.

Список значений, разделенных запятыми (,), обозначает перечень. Например, перечисление 3, 4, 6, 8 означает четыре указанных целых числа.

Косая черта (/) используется для определения шага значений. Целочисленное значение может быть пропущено в диапазоне, если после диапазона указать / < целое >. Например, значение минут 0-59/2 , определяет, что будет пропущена каждая вторая минута. В качестве шага значений также может быть указана звёздочка. Например, значение месяца */3 определяет, что будет пропущен каждый третий месяц.

Любые строки, начинающиеся с символа решетки (#), являются комментариями, и не обрабатываются.

Пример 22-1. Примеры файлов crontab

# record the memory usage of the system every monday # at 3:30AM in the file /tmp/meminfo 30 3 * * mon cat /proc/meminfo >> /tmp/meminfo # run custom script the first day of every month at 4:10AM 10 4 1 * * /root/scripts/backup.sh

Как видно из файла /etc/crontab , в нём используется сценарий run-parts , чтобы запускающий сценарии в каталогах /etc/cron.hourly , /etc/cron.daily , /etc/cron.weekly и /etc/cron.monthly соответственно ежечасно, ежедневно, еженедельно и ежемесячно. Файлы в этих каталогах должны быть сценариями оболочки.

Если задачи cron должны выполняться по расписанию, но не ежечасно, ежедневно, еженедельно или ежемесячно, их можно добавить в каталог /etc/cron.d . Все файлы в этом каталоге имеют тот же синтаксис, что и /etc/crontab .

Демон cron каждую минуту ищет изменения в файле etc/crontab и каталогах etc/cron.d/ и /var/spool/cron . Если какие-либо изменения будут найдены, они загружаются в память. Таким образом, демон не нуждается в перезапуске при изменении файла crontab.

Другие пользователи (не root) также могут настраивать задачи cron, используя программу crontab . Все созданные пользователями файлы crontab, хранятся в каталоге /var/spool/cron и выполняются, от имени создавшего их пользователя. Чтобы создать файл crontab для пользователя, войдите в систему под его именем и введите команду crontab -e , чтобы отредактировать crontab пользователя, с помощью редактора, указанного в значении переменной окружения VISUAL или EDITOR . Этот файл использует тот же формат, что и /etc/crontab . Когда изменения фала crontab будут сохранены, этот файл crontab будет записан в соответствии с именем пользователя, под названием /var/spool/cron/ username .

Запуск и остановка службы

Чтобы запустить службу cron, выполните следующую команду: /sbin/service crond start . Чтобы остановить её, выполните команду: /sbin/service crond stop . Рекомендуется, чтобы эта служба запускалась при загрузке системы. Обратитесь к Главе 8 за указаниями по настройке автоматического запуска службы cron при загрузке системы.

Источник

Оцените статью
Adblock
detector