Linux what is cron

What is cron on a Linux or Unix-like systems?

C an you explain what is Cron? Why do I need to cron service on a Linux, OS X, and Unix-like systems?

Cron is UNIX/Linux/BSD service or daemon to execute commands or scripts at given time and date. It is also known as the clock daemon that executes commands at specified dates and times according to instructions in a file.[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

[/donotprint]

Generally, crontab uses a daemon, crond, which runs constantly in the background and checks once a minute to see if any of the scheduled jobs need to be executed. If so, it executes them. These jobs are generally referred to as cron jobs.

Cron is controlled by a set of files called “crontabs”. There is the master file in /etc/crontab. Each users cronjob is stored in /var/spool/cron/username directory. To see master file type the following cat command:
$ cat /etc/crontab
Sample outputs:

Editing Crontab or setting up your own job

Just type following command:
$ crontab -e
To list your own jobs type the following command:
$ crontab -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How do I configure and install my own cron jobs?

See our tutorial on how to automatically run given commands or scripts at a specified time and date:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Настройка Cron

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

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

Как работает Cron?

Фактически, Cron — это сервис, как и большинство других сервисов Linux, он запускается при старте системы и работает в фоновом режиме. Его основная задача выполнять нужные процессы в нужное время. Существует несколько конфигурационных файлов, из которых он берет информацию о том что и когда нужно выполнять. Сервис открывает файл /etc/crontab, в котором указаны все нужные данные. Часто, в современных дистрибутивах там прописан запуск утилиты run-parts, которая запускает нужные скрипты из следующих папок:

  • /etc/cron.minutely — каждую минуту;
  • /etc/cron.hourly — каждый час;
  • /etc/cron.daily — каждый день;
  • /etc/cron.weekly — каждую неделю;
  • /etc/cron.monthly — каждый месяц.

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

Она позволяет выполнять их даже если компьютер работает не всегда и время от времени выключается. Дата выполнения задания последний раз записывается в файл /var/spool/anacron, а затем, при следующем запуске anacron проверяет был ли запущен нужный процесс в нужное время, и если нет, то запускает его. Сам же сервис cron больше рассчитан на выполнение задач в течение дня или с точно расписанным временем и датой.

Настройка Cron

Для настройки времени, даты и интервала когда нужно выполнять задание используется специальный синтаксис файла cron и специальная команда. Конечно, вы всегда можете отредактировать файл /etc/crontab, но этого делать не рекомендуется. Вместо этого, есть команда crontab:

Ее всегда желательно выполнять с опцией -e, тогда для редактирования правил будет использован ваш текстовый редактор по умолчанию. Команда открывает вам временный файл, в котором уже представлены все текущие правила cron и вы можете добавить новые. После завершения работы команды cron файл будет обработан и все правила будут добавлены в /var/spool/cron/crontabs/имя_пользователя причем добавленные процессы будут запускаться именно от того пользователя, от которого вы их добавляли.

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

Синтаксис crontab

Как я уже говорил, время задается особым синтаксисом, давайте рассмотрим синтаксис настройки одной задачи cron:

минута час день месяц день_недели /путь/к/исполняемому/файлу

Нужно сказать, что обязательно нужно писать полный путь к команде, потому что для команд, запускаемых от имени cron переменная среды PATH будет отличаться, и сервис просто не сможет найти вашу команду. Это вторая самая распространенная причина проблем с Cron. Дата и время указываются с помощью цифр или символа ‘*’. Этот символ означает, что нужно выполнять каждый раз, если в первом поле — то каждую минуту и так далее. Ну а теперь перейдем к примерам.

Примеры настройки cron

Сначала можно посмотреть задачи cron для суперпользователя, для этого можно воспользоваться опцией -l:

Вы можете удалить все существующие задачи командой -r:

Давайте предположим, что нам нужно запускать от имени суперпользователя наш скрипт по адресу /usr/local/bin/serve. Какой-нибудь обслуживающий скрипт. Самый простой пример — запускать его каждую минуту:

Далее, усложним, будем запускать каждый час, в нулевую минуту:

Запускаем в нулевую минуту нулевого часа, каждый день, это в 12 ночи:

0 0 * * * /usr/local/bin/serve

Если идти так дальше, то можно запускать в первый день каждого месяца:

0 0 1 * * /usr/local/bin/serve

Можно в любой день, например, 15 числа:

0 0 15 * * /usr/local/bin/serve

В первый день недели первого месяца года, 0 часов 0 минут:

0 0 * 1 0 /usr/local/bin/serve

Или в нулевой день недели каждого месяца:

0 0 * * 0 /usr/local/bin/serve

Вы можете выбрать любую минуту, час и день недели, например, 15.30 во вторник:

30 15 * * 2 /usr/local/bin/serve

Понедельник считается первым днем, воскресенье — это седьмой или нулевой день. Еще можно писать сокращенное название дня недели, например sun — воскресенье:

30 15 * * sun /usr/local/bin/serve

Для того чтобы указать определенный интервал нужно использовать символ «-«, например, каждый час, с семи утра до семи вечера:

0 7-19 * * * /usr/local/bin/serve

Если нужно запустить команду несколько раз, можно использовать разделитель «,». Например, запустим скрипт в 5 и 35 минут пятого (16:05 и 16:35), каждый день:

5,35 16 * * * /usr/local/bin/serve

Вы можете захотеть не указывать отдельно время, а просто указать интервал, с которым нужно запускать скрипт, например, раз в 10 минут. Для этого используется разделитель косая черта — «/»:

Кроме того, для некоторых часто используемых наборов были придуманы переменные, вот они:

  • @reboot — при загрузке, только один раз;
  • @yearly, @annually — раз год;
  • @monthly — раз в месяц;
  • @weekly — раз в неделю;
  • @daily, @midnight — каждый день;
  • @hourly — каждый час.

Например, вот так просто будет выглядеть команда запуска скрипта раз в час:

Если же вы собрались добавить скрипт в одну из папок, то, как я уже говорил, нужно чтобы его имя было без точек и у него были права на выполнение:

sudo vi /etc/corn.daily/basckup

Скрипт должен выглядеть подобным образом. Теперь вы знаете как настроить cron, осталось проверить как все работает.

Отладка работы

После того как вы настроили правила, еще хотелось бы проверить работают ли они. Для этого ждем того времени, когда скрипт уже должен быть выполнен и смотрим лог cron. Иногда он находится в /var/log/cron, а иногда пишется в syslog. Например, у меня в crontab есть такая строка:

Она должна выполняться в 19.40 каждый день, теперь смотрим лог:

grep CRON /var/log/syslog

И видим что в нашем логе она действительно есть и выполняется целиком успешно. Если бы были какие-либо ошибки, то тут же было бы выведено сообщение.

Если нужно проверить скрипт, который находится в одной из специализированных папок, то тут еще проще, просто запустите run-paths, передав ей в параметр нужную папку или даже сам скрипт:

sudo run-paths /etc/cron.daily/

Дальше вы увидите весь вывод, включая вывод скрипта и сможете быстро понять в чем проблема.

Выводы

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

Источник

Linux what is cron

This article describes how to setup and use cron daemons in Gentoo Linux.

Contents

Cron basics

What cron does

Cron is a daemon that runs scheduled tasks based on input from the command crontab . It accomplishes this task by waking up every minute and checking to see if there are any cron-jobs to run in any of the user crontabs.

The de facto cron

There are a few cron implementations to choose from in Portage. All of them offer a similar interface, namely the use of crontab or a similar command. There is also a related utility called Anacron which is meant to work with cron on systems that are not continuously running.

All of the available cron packages depend on sys-process/cronbase. This package is not technically depended on by any of the cron packages, but it does provide cron-like functionality that most users can appreciate.

Before getting started working with cron, a proper cron implementation has to be selected.

Which cron is right for the job?

cronie

Cronie (sys-process/cronie) is a fork of now outdated vixie-cron done by Fedora, which is still maintained. Because of it being a fork it has the same feature set the original vixie-cron provides. Additionally cronie comes with an anacron implementation which is enabled, by default, through the anacron USE flag. Be aware of the configuration differences as noted in bug #551352 when migrating from another cron system. Expected jobs may not run at all.

dcron (Dillon’s Cron)

Dcron aims to be a simple, elegant and secure implementation of cron. It does not allow the specification of environment variables in crontabs and all cron-jobs are run from /bin/sh . Like vixie-cron, each user has his own crontab. As of version 4 it contains anacron-like features. Latest version is 4.5 released in May 2011.

  • Fast, simple and free of unnecessary features;
  • Access to crontab is limited to the cron group, i.e. it doesn’t rely on any external faculties.

fcron

Fcron aims at replacing vixie-cron and anacron. It is designed to work on systems that are not continuously running and it is packed with extra features. It has job startup constraints, job serialization controls, the ability to assign nice values to jobs and the ability to schedule jobs to run at system startup. See fcron’s home page for more information. Latest versions released were 3.2.1 in June 2016 and 3.3.0 (dev) in August 2016, development on GitHub continues sparsely.

  • Designed to work on systems that are not continuously running, i.e. it can run a job after restarting if it was missed;
  • Setting of environment variables and many other options in crontabs;
  • Enhanced crontab syntax with support for many new features;
  • Each user can have a personal crontab, access is controlled by cron.allow and cron.deny

bcron

Bcron is a new cron system designed with secure operations in mind. To do this, the system is divided into several separate programs, each responsible for a separate task, with strictly controlled communications between them. The user interface is a drop-in replacement for similar systems (such as vixie-cron), but the internals differ greatly. For more information, see the bcron homepage at http://untroubled.org/bcron. Latest version is 0.11 released in August 2015.

  • Drop-in replacement for vixie-cron;
  • Multiprocess design;
  • Native daylight savings time support.

anacron

Anacron is not a cron daemon, it is something that usually works in conjunction with one. It executes commands at intervals specified in days and it does not assume that the system is running continuously; it will run jobs that were missed while the system was down. Anacron usually relies on a cron daemon to run it each day.

Using cron

Installation

Select the right cron implementation for the job, and then emerge it:

Make sure the cron daemon of choice has been added to the system’s init process; without this step the cron daemon will not perform its job.

Optionally, if Fcron or dcron have not been installed, installing Anacron as a helper to the cron daemon might be a wise choice.

Again, do not forget to add anacron to the system’s init process.

For anacron, there is usually no init process. Instead, anacron needs to be launched through a different cron implementation.

One method is to launch anacron through a cron definition. By default, it installs an hourly run script, which is consumed by most cron implementations by default. If that isn’t the case though, then it can still be launched through manual definitions:

System crontab

The post install messages from some of these cron packages instruct the user to run crontab /etc/crontab . The /etc/crontab file is the system crontab. A cron installation can use it in conjunction with sys-process/cronbase to run the scripts in /etc/cron.. Note that only cronie schedules jobs in /etc/crontab automatically. Dcron users will need to run crontab /etc/crontab every time changes are made to the /etc/crontab file. Fcron users need to run emerge —config sys-process/fcron to configure the system crontab.

Please note that jobs scheduled in the system crontab might not show up in the list of cron-jobs displayed by running crontab -l .

Of course, users can choose not to use any system crontab at all. If dcron or fcron has been chosen, do not run crontab /etc/crontab . If cronie or bcron has been chosen comment all lines in /etc/crontab .

A quick and easy way to comment out all the lines in a file is by using the sed command. Run the following command to comment out all the lines in etc/crontab

Giving trusted users access to cron

For users other than root to have access to the cron daemon, read this section, otherwise proceed to the next section: Scheduling cron-jobs.

No matter which cron package has been chosen, to allow a user to use crontab he will first have to be in the cron group. As an example, to add the user larry to the cron group run:

dcron

When using dcron, the above step is all that is needed to give a user access to crontab. Dcron users may proceed to the next section Scheduling cron-jobs, all others need to keep reading.

fcron

When using fcron, edit the /etc/fcron/fcron.deny and /etc/fcron/fcron.allow files. The most secure way to run a system is to first deny all users in /etc/fcron/fcron.deny , and then explicitly allow users in /etc/fcron/fcron.allow .

If a user (larry again for this example) should be able to schedule his own cron-jobs, then add him to /etc/fcron/fcron.allow as follows:

cronie

If cronie has been chosen, then simply edit the /etc/cron.allow file.

For example, to allow access to the user larry, add him to /etc/cron.allow as follows:

Scheduling cron-jobs

The process of editing crontabs is different for each package, but they all support the same basic set of commands: adding and replacing crontabs, editing crontabs, deleting crontabs, and listing cron-jobs in crontabs. The following list shows how to run various commands for each package.

Version Edit crontab Remove crontab New crontab List cron-jobs
dcron crontab -e crontab -d [user] crontab file crontab -l
fcron fcrontab -e fcrontab -r [user] fcrontab file fcrontab -l
cronie and bcron crontab -e crontab -r -u [user] crontab file crontab -l

Before any of these commands can be used, first understanding of the crontab itself is needed. Each line in a crontab specifies five time fields in the following order: the minutes (0-59), hours (0-23), days of the month (1-31), months (1-12), and days of the week (0-7, Monday is day 1, Sunday is day 0 and day 7). The days of the week and months can be specified by three-letter abbreviations like mon, tue, jan, feb, etc. Each field can also specify a range of values (e.g. 1-5 or mon-fri), a comma separated list of values (e.g. 1,2,3 or mon,tue,wed) or a range of values with a step (e.g. 1-6/2 as 1,3,5).

That sounds a little confusing, but with a few examples it is easy to see it is not as complicated as it sounds.

To test what was just covered go through the steps of actually inputting a few cron-jobs. First, create a file called crons.cron and make it look like the this:

Now add that crontab to the system with the «new command» from the table above.

To verify the scheduled cron-jobs, use the proper list command from the table above.

A list resembling crons.cron should be displayed; if not maybe the wrong command was issued to input the crontab.

This crontab should echo «I really like cron» every minute of every hour of every day every other month. Obviously a user would only do that if they really liked cron. The crontab will also echo «I like cron a little» at 16:30 every day in January and February. It will also echo «I don’t really like cron» at 3:10 on the January 1st.

If using anacron keep reading this section. Otherwise, proceed to the next section on Editing crontabs.

Anacron users will want to edit /etc/anacrontab . This file has four fields: the number of days between each run, the delay in minutes after which it runs, the name of the job, and the command to run.

For example, to have it run echo «I like anacron» every 5 days, 10 minutes after anacron is started, enter the following:

Anacron exits after all of the jobs in anacrontab have finished. To check to see if these jobs should be performed every day, a cron daemon will be used. The instructions at the end of the next section explain how this should be handled.

Editing crontabs

Being realistic, no user would want their system telling them how much they like cron every minute. As a step forward, remove the previous example crontab using the corresponding remove command from the table above. Use the corresponding list command to view the cron-jobs afterward to make sure it worked.

No cron-jobs should be displayed in the output from crontab -l . If cron jobs are listed, then the remove command failed to remove the crontab; verify the correct remove command for the system’s cron package.

Now that we have a clean state, let’s put something useful into the root crontab. Most people will want to run updatedb on a weekly basis to make sure that mlocate works properly. To add that to the system’s crontab, first edit crons.cron again so that it looks like the following:

That would make cron run updatedb at 2:22 A.M. on Monday morning every week. Now input the crontab with the proper new command from the table above, and check the list again.

Now let’s say emerge —sync should be ran on a daily schedule in order to keep the Portage tree up to date. This could be done by first editing crons.cron and then using crontab crons.cron as was done in the example above, or by using the proper edit command from the table above. This provides a way to edit the user’s crontab in situ, without depending on external files like crons.cron .

The above command should open the user’s crontab with an editor. For example, if emerge —sync is to be run every day at 6:30 A.M., make the crontab look something like this:

Again, check the cron-jobs list as done in the previous examples to make sure the jobs are scheduled. If they are all there, then the system is ready to rock and roll.

Using cronbase

As mentioned earlier, all of the available cron packages depend on sys-process/cronbase. The cronbase package creates /etc/cron., and a script called run-crons . Notice the default /etc/crontab file contains something like this:

To avoid going into much detail, assume these commands will effectively run hourly, daily, weekly and monthly scripts. This method of scheduling cron-jobs has some important advantages:

  • They will run even if the computer was off when they were scheduled to run;
  • It is easy for package maintainers to place scripts in those well defined places;
  • The administrators know exactly where the cron-jobs and crontab are stored, making it easy to backup and restore these parts of their systems.

Using anacron

As mentioned earlier, anacron is used on systems not meant to be run continuously (like most of the desktop installations). Its default configuration file, /etc/anacrontab , is usually similar to the following:

The main difference between this and other common crontabs is that with anacron there is no fixed date/hour for the job scheduling, but only the period between every run. When anacron is started, it will check the contents of a set of files in /var/spool/anacron and calculate if the corresponding entry in the configuration file has expired since the last run. If it has, then the command is invoked again.

As a final note, it is important to comment out any overlapping entry in any other cron installed in the system, such as in the following vixie-cron crontab example:

Without doing this, the daily, weekly, and monthly parts will be executed — at different times — by both the cron daemon and anacron, leading to possible double job executions.

Troubleshooting

When having problems getting cron to work properly, this quick checklist might be helpful.

Remember, each cron package is different and the range of features varies greatly. Be sure to consult the man pages for crontab, fcrontab, or anacrontab, depending on which cron daemon has been activated!

Is cron running?

To verify that cron is running, see if it shows up in the process list:

Is cron working?

Try the following:

Then check if /tmp/file_you_own.log is modified periodically.

Is the command working?

Same as before, but perhaps redirect the standard error output as well:

Can cron run the job?

Check the cron log, usually /var/log/cron.log or /var/log/messages for errors.

Are there any dead.letter s?

cron usually sends mail when there is a problem; check for mail and look for the creation of a

Why are cron mails not sent out?

In order to receive mails from cron, a valid MTA setup must be implemented. This is provided by any package from virtual/mta.

If the cron mails are only to be sent locally, and not through a fully configured mail server, the system can use mbox ( /var/spool/mail ) mails, by enabling the mbox useflag with the respective package which provides the MTA.

Cron jobs alternatives

Some hosting companies do not allow access to cron, but many cron jobs alternatives can be found which are free or commercially available:

Источник

Читайте также:  Что такое xnview windows
Оцените статью