Linux var spool cron

Использование CRON и команды crontab

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

Cron это программа, выполняющая задания по расписаню. Позволяет неоднократный запуск заданий. Т.е. задание можно запустить в определенное время или через определенный промежуток времени. Формат и значения полей, для пользовательских файлов crontab, будут приведены в конце статьи.

При загрузке системы, запускается демон cron и проверяет очередь заданий at и заданий пользователей в файлах crontab. При запуске, демон cron сначала проверяет каталог /var/spool/cron на наличие файлов crontab, файлы crontab имеют имена пользователей, соответствующие именам пользователей из /etc/passwd Каждый пользователь может иметь только один файл crontab, записей в файле может быть несколько.

Другими словами — файлы crontab содержат инструкции для демона cron, который запустит задание(я) описаное в файле crontab. Все файлы crontab из каталога /var/spool/cron загружаются в память, одновременно с ними загружаются файлы из /etc/cron.d После этого демон cron загружает содержимое файла /etc/crontab При стандартных настройках, содержимое /etc/crontab имеет следующий вид:

Информация файла указывает, что:

  • содержимое каталога /etc/cron.hourly будет запускаться каждый час на первой минуте часа.
  • содержимое каталога /etc/cron.daily будет запускаться каждый день на второй минуте четвертого часа.
  • содержимое каталога /etc/cron.weekly будет запускаться каждое воскресенье на 22’ой минуте 4’го часа.
  • содержимое каталога /etc/cron.monthly будет запускаться каждый первый день месяца на 42’ой минуте 4’го часа.

SHELL=/bin/bash означает использовать для запуска команд /bin/bash , если переменная не указана, то значение будет взято из /etc/passwd для пользователя являющимся владельцем файла.

HOME=/ корневой каталог для пользователя (параметр не обязательный) При необходимости доступа к специальным свойствам интерпретатора, значения переменных SHELL и HOME можно изменить, не зависимо от того, что прописано в /etc/passwd

MAILTO=root означает кому отсылать сообщение о результате работы команд.

Все содержимое из этих каталогов будет запускаться с правами доступа пользователя root и файлы должны иметь права доступа на «выполнение» (про права доступа читай статью http://rst.void.ru/texts/chmod.txt) Поэтому перед размещением файлов в одном из этих каталогов необходимо убедиться, что сценарии не насесут вред системе.

После того, как демон cron запущен и прочел содержимое всех файлов crontab, он бездействует, просыпаясь каждую минуту и проверяя не требуется ли запуск какой-либо команды в данную минуту, или не появился ли новый файл crontab который необходимо обработать. Демон cron определяет изменения по времени модификации файлов или каталогов, такое его свойство избавляет от необходимости перезапуска демона.

Как отмечалось выше, размещение файлов для cron в каталогах

доступно только пользователю root, для использования файлов crontab пользователями, нужно использовать команду crontab. Команда служит для создания, изменения и добавления файла для демона cron

Пример

Рассмотрим пример создания файла crontab для пользователя user ,домашняя директория /home/user

Задача: запускать каждую минуту файл /home/user/mail, который будет отправлять почту

1.Создаем временный файл /home/user/test содержимое файла test такое:

2. Запускаем в терминале команду crontab /home/user/test

Все. После этого в каталоге /var/spool/cron будет создан файл «user» примерно с таким содержимым

и файл /home/user/mail будет запускаться демоном cron каждую минуту.

Доступ в каталог /var/spool/cron непривилегированому пользователю закрыт, что бы посмотреть юзером «user» есть ли у него файл crontab ,достаточно набрать команду crontab -l , если файл существует-будет показано его содержимое.

Для удаления файла используется команда crontab -r

Для редактирования crontab -e

Для управления файлами crontab пользователем «root» используется синтаксис:

-u означает чей crontab будет обработан, Если опция не задана, то будет обработан crontab того пользователя, который запустил команду crontab.

Формат и значения полей

Каждая команда в пользовательском файле crontab занимает одну строку и состоит из шести полей. Пользовательские файлы crontab находятся в каталоге /var/spool/cron

Общий формат команды:

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

равнозначная предыдущему примеру запись (списком)

то же самое с указанием диапазона

Для отладки задания cron, можно перенаправить результат в файл

Если при запуске команды /home/user/mail возникнут ошибки, то они будут записаны в файл /tmp/tmp.cron и вы всегда сможете узнать причину. В случае перенаправления вывода в файл, письмо, юзеру указаному в переменной MAILTO отправлено не будет.

Читайте также:  Оптимизация windows после установки ssd

Посмотреть информацию о всех командах запускаемых демоном cron можно в каталоге /var/log называются cron, cron1 и т.д.

В файле /var/log/cron записано время запуска всех заданий cron за предыдущий день

В остальных файлах cron1,cron2 находится подобная информация, но более старая чем в cron

Вот практически и все, что требуется знать для использования cron и crontab.

Источник

Linux var spool cron

cron is the time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times, dates or intervals. It is commonly used to automate system maintenance or administration.

Contents

Installation

There are many cron implementations, but none of them are installed by default as the base system uses systemd/Timers instead. See the Gentoo’s cron guide, which offers comparisons.

Configuration

Activation and autostart

After installation, the daemon will not be enabled by default. The installed package likely provides a service, which can be controlled by systemctl. For example, cronie uses cronie.service .

Check /etc/cron.daily/ and similar directories to see which jobs are present. Activating cron service will trigger all of them.

Handling errors of jobs

cron registers the output from stdout and stderr and attempts to send it as email to the user’s spools via the sendmail command. Cronie disables mail output if /usr/bin/sendmail is not found. In order for mail to be written to a user’s spool, there must be an smtp daemon running on the system, e.g. opensmtpd . Otherwise, you can install a package that provides the sendmail command, and configure it to send mail to a remote mail exchanger. You can also log the messages by using the -m option and writing a custom script.

  1. Edit the cronie.service unit.
  2. Install esmtpAUR , msmtp, opensmtpd , sSMTP, or write a custom script.

Example with sSMTP

sSMTP is a send-only sendmail emulator which delivers email from a local computer to an smtp server. While there are currently no active maintainers, it is still by far the simplest way to transfer mail to a configured mailhub. There are no daemons to run, and configuration can be as simple as editing 3 lines in a single configuration file (if your host is trusted to relay unauthenticated email through your mailhub). sSMTP does not receive mail, expand aliases, or manage a queue.

Install ssmtp AUR , which creates a symbolic link from /usr/bin/sendmail to /usr/bin/ssmtp . You must then edit /etc/ssmtp/ssmtp.conf . See sSMTP for details. Creating a symbolic link to /usr/bin/sendmail insures that programs like S-nail (or any package which provides /usr/bin/mail ) will just work without modification.

Restart cronie to insure that it detects that you now have a /usr/bin/sendmail installed.

Example with msmtp

Install msmtp-mta , which creates a symbolic link from /usr/bin/sendmail to /usr/bin/msmtp . Restart cronie to make sure it detects the new sendmail command. You must then provide a way for msmtp to convert your username into an email address.

Then either add MAILTO line to your crontab, like so:

or create /etc/msmtprc and append this line:

and create /etc/aliases :

Then modify the configuration of cronie daemon by replacing the ExecStart command with:

Example with esmtp

After installation configure the routing:

Procmail needs root privileges to work in delivery mode but it is not an issue if you are running the cronjobs as root anyway.

To test that everything works correctly, create a file message.txt with «test message» in it.

From the same directory run:

You should now see the test message and the time and date it was sent.

The error output of all jobs will now be redirected to /var/spool/mail/user_name .

Due to the privileged issue, it is hard to create and send emails to root (e.g. su -c «» ). You can ask esmtp to forward all root’s email to an ordinary user with:

/.esmtprc with the same content.

Run the following command to make sure it has the correct permission:

Then repeat the test with message.txt exactly as before.

Example with opensmtpd

Edit /etc/smtpd/smtpd.conf . The following configuration allows for local delivery:

You can proceed to test it. First start smtpd.service . Then do:

user can check their mail in with any reader able to handle mbox format, or just have a look at the file /var/spool/mail/user . If everything goes as expected, you can enable opensmtpd for future boots.

This approach has the advantage of not sending local cron notifications to a remote server. On the downside, you need a new daemon running.

Читайте также:  Технические характеристики windows server 2019

Long cron job

Suppose this program is invoked by cron :

What happens is this:

  1. cron runs the script
  2. as soon as cron sees some output, it runs your MTA, and provides it with the headers. It leaves the pipe open, because the job has not finished and there might be more output.
  3. the MTA opens the connection to postfix and leaves that connection open while it waits for the rest of the body.
  4. postfix closes the idle connection after less than an hour and you get an error like this :

To solve this problem you can use the command chronic or sponge from moreutils . From their respective man page:

chronic chronic runs a command, and arranges for its standard out and standard error to only be displayed if the command fails (exits nonzero or crashes). If the command succeeds, any extraneous output will be hidden. sponge sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file… If no output file is specified, sponge outputs to stdout.

Chronic too buffers the command output before opening its standard output.

Crontab format

The basic format for a crontab is:

  • minute values can be from 0 to 59.
  • hour values can be from 0 to 23.
  • day_of_month values can be from 1 to 31.
  • month values can be from 1 to 12.
  • day_of_week values can be from 0 to 6, with 0 denoting Sunday.

Spaces are used to separate fields. To fine-tune your schedule you may also use one of the following symbols:

Symbol Description
* Wildcard, specifies every possible time interval
, List multiple values separated by a comma.
Specify a range between two numbers, separated by a hyphen
/ Specify a periodicity/frequency using a slash

For example, the line:

will execute the script i_love_cron.sh at five minute intervals from 9 AM to 4:55 PM on weekdays except during the summer months (June, July, and August).

In addition, crontab has some special keywords:

will execute the script i_love_cron.sh at startup.

More examples and advanced configuration techniques can be found below.

Basic commands

Crontabs should never be edited directly; instead, users should use the crontab program to work with their crontabs. To be granted access to this command, user must be a member of the users group (see the gpasswd command).

To view their crontabs, users should issue the command:

To edit their crontabs, they may use:

To remove their crontabs, they should use:

If a user has a saved crontab and would like to completely overwrite their old crontab, they should use:

To overwrite a crontab from the command line (Wikipedia:stdin), use

To edit somebody else’s crontab, issue the following command as root:

This same format (appending -u username to a command) works for listing and deleting crontabs as well.

Examples

runs the command /bin/echo Hello, world! on the first minute of every hour of every day of every month (i.e. at 12:01, 1:01, 2:01, etc.).

runs the same job every five minutes on weekdays during the month of January (i.e. at 12:00, 12:05, 12:10, etc.).

The line (as noted in «man 5 crontab»):

will execute the script i_love_cron.sh at five minute intervals from 9 AM to 5 PM (excluding 5 PM itself) every weekday (Mon-Fri) of every month except during the summer (June, July, and August).

Periodical settings can also be entered as in this crontab template:

Here are some self-explanatory crontab syntax examples:

Default editor

To use an alternate default editor, define the EDITOR environment variable in a shell initialization script as described in Environment variables.

As a regular user, su will need to be used instead of sudo for the environment variable to be pulled correctly:

To have an alias to this printf is required to carry the arbitrary string because su launches in a new shell:

Running X.org server-based applications

Cron does not run under the X.org server therefore it cannot know the environmental variable necessary to be able to start an X.org server application so they will have to be defined. One can use a program like xuserrun-git AUR to do it:

Or they can be defined manually ( echo $DISPLAY will give the current DISPLAY value):

If running notify-send for desktop notifications in cron, notify-send is sending values to dbus. So it needs to tell dbus to connect to the right bus. The address can be found by examining DBUS_SESSION_BUS_ADDRESS environment variable and setting it to the same value. Therefore:

Читайте также:  Nfs mac os sierra

If done through say SSH, permission will need be given:

Asynchronous job processing

If you regularly turn off your computer but do not want to miss jobs, there are some solutions available (easiest to hardest):

Cronie

cronie comes with anacron included. The project homepage says:

Cronie contains the standard UNIX daemon crond that runs specified programs at scheduled times and related tools. It is based on the original cron and has security and configuration enhancements like the ability to use pam and SELinux.

Dcron

Vanilla dcron AUR supports asynchronous job processing. Just put it with @hourly, @daily, @weekly or @monthly with a jobname, like this:

Cronwhip

cronwhip AUR is a script to automatically run missed cron jobs; it works with the former default cron implementation, dcron. See also the forum thread.

Anacron

Anacron is a full replacement for dcron which processes jobs asynchronously.

It is provided by cronie . The configuration file is /etc/anacrontab . Information on the format can be found in the anacrontab(5) man page. Running anacron -T will test /etc/anacrontab for validity.

Fcron

Like anacron, fcron assumes the computer is not always running and, unlike anacron, it can schedule events at intervals shorter than a single day which may be useful for systems which suspend/hibernate regularly (such as a laptop). Like cronwhip, fcron can run jobs that should have been run during the computer’s downtime.

When replacing cronie with fcron be aware the spool directory is /var/spool/fcron and the fcrontab command is used instead of crontab to edit the user crontabs. These crontabs are stored in a binary format with the text version next to them as foo.orig in the spool directory. Any scripts which manually edit user crontabs may need to be adjusted due to this difference in behavior.

A quick scriptlet which may aide in converting traditional user crontabs to fcron format:

Ensuring exclusivity

If you run potentially long-running jobs (e.g., a backup might all of a sudden run for a long time, because of many changes or a particular slow network connection), then flock ( util-linux ) can ensure that the cron job will not start a second time.

Cronie

The relevant file hierarchy for cronie is the following:

Cronie provides both cron and anacron functionalities: cron runs jobs at regular time intervals (down to a granularity of one minute) as long as the system is available at the specified time, while anacron executes commands at intervals specified in days. Unlike cron, it does not assume that the system is running continuously. Whenever the system is up, anacron checks if there are any jobs that should have been run and handles them accordingly.

A cron job can be defined in a crontab-like file in the /etc/cron.d directory or added within the /etc/crontab file. Note the latter is not present by default but is used if it exists. As instructed by /etc/cron.d/0hourly , any executable file in /etc/cron.hourly will be run every hour (by default at minute 1 of the hour). Files in /etc/cron.minutely are executed every minute if instructed accordingly in /etc/cron.d/0hourly . The executables are typically shell scripts, symlinks to executable files can also be used. The /etc/cron.deny file includes the list of users not allowed to use crontab, without this file, only users listed in /etc/cron.allow can use it.

Anacron works similarly, by executing the files in the /etc/cron.daily , /etc/cron.weekly and /etc/cron.monthly directories, placed there depending on the desired job frequency. The cron job /etc/cron.hourly/0anacron makes sure that anacron is run once daily to perform its pending tasks.

Dcron

The cron daemon parses a configuration file known as crontab . Each user on the system can maintain a separate crontab file to schedule commands individually. The root user’s crontab is used to schedule system-wide tasks (though users may opt to use /etc/crontab or the /etc/cron.d directory, depending on which cron implementation they choose).

These lines exemplify one of the formats that crontab entries can have, namely whitespace-separated fields specifying:

  1. @period
  2. ID=jobname (this tag is specific to dcron)
  3. command

The other standard format for crontab entries is:

The crontab files themselves are usually stored as /var/spool/cron/username . For example, root’s crontab is found at /var/spool/cron/root

See the crontab man page for further information and configuration examples.

Источник

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