Cron linux как добавить задание
Перейти к содержимому

Cron linux как добавить задание

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7d99e6d74b4d77b3 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Как добавить команду в Cron

При администрировании и настройке серверов очень часто надо настраивать автоматическое выполнение определенных скриптов или программ через равные промежутки времени. Это может быть резервное копирование, отправка отчётов о состоянии сервера или другие тому подобные вещи.

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

Как посмотреть задания cron

Думаю, что начать следует не с настройки, а именно как посмотреть уже настроенные задачи cron. На самом деле задачи хранятся в трёх местах:

  • База данных crontab — здесь хранятся все записи cron пользователя, которые вы настраиваете вручную;
  • /etc/crontab и /etc/cron.d/ — системные записи cron и записи cron различных пакетов;
  • /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly — здесь лежат скрипты, которые надо выполнять раз в час, день, неделю и месяц соответственно, обычно эти папки используются различными пакетами, но вы тоже можете их использовать для своих скриптов.

Чтобы посмотреть задания cron добавленные текущим пользователем используйте команду crontab и опцию -l:

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

sudo crontab -u root -l

А теперь давайте поговорим о том, как добавить команду cron для нужного вам пользователя.

Добавление команды в cron

Чтобы добавить задание cron из терминала можно использовать утилиту crontab. Для открытия временного файла с текущими заданиями этого пользователя выполните:

Все запланированные действия будут выполнятся от текущего пользователя, если вы хотите указать другого пользователя используйте опцию -u:

sudo crontab -u имя_пользователя -e

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

Каждая задача формируется следующим образом:

минута(0-59) час(0-23) день(1-31) месяц(1-12) день_недели(0-7) /полный/путь/к/команде

Чтобы подставить любое значение используйте звездочку «*«. Первые пять параметров характеризуют время выполнения, а последний, это путь к команде или скрипту, который нужно выполнить. Обратите внимание, что значение переменной PATH здесь не действует, поэтому путь надо писать полностью либо объявлять свою переменную PATH в начале файла настройки. Давайте сделаем простой скрипт, который будет выводить в лог дату своего запуска и поможет отладить всё это:

sudo vi /usr/local/bin/script.sh

#!/bin/bash
echo $(date) >> /var/log/testcron.log

Сделайте скрипт исполняемым:

sudo chmod ugo+x /usr/local/bin/script.sh

Самый простой пример как запускать cron каждую минуту. Вместо всех параметров ставим просто звездочку:

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

Можно указать несколько значений через запятую, для того чтобы определить несколько точек запуска. Например, будем запускать скрипт cron каждые 15 минут:

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

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

Чтобы запустить cron каждые 10 минут используйте:

А для запуска cron каждые 30 минут:

Аналогичным образом задаются часы, например, выполнять скрипт только 6:00 и 18:00:

0 6,18 * * * /usr/local/bin/script.sh

А вот запустить cron каждую секунду или раз в 30 секунд не получится. Минимальная единица времени в cron это минута. Но можно создать команду, которая будет запускаться раз в минуту и по 30 секунд спать и затем снова делать:

* * * * * /usr/local/bin/script.sh && sleep 30 && /usr/local/bin/script.sh

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

  • @reboot — при перезагрузке;
  • @yearly, @annually — раз в год (0 0 1 1 *);
  • @monthly — раз в месяц (0 0 1 * *);
  • @weekly — раз в неделю (0 0 * * 0);
  • @daily, @midnight — раз в день в полночь (0 0 * * *);
  • @hourly — раз в час (0 * * * *).

Для подбора правильной комбинации даты можно использовать сервис crontab.guru. Он позволяет в реальном времени посмотреть когда будет выполнено то или иное условие:

Когда настройка cron linux будет завершена, сохраните изменения и закройте файл. Для этого в Nano нажмите Ctrl+O для сохранения и Ctrl+X для закрытия редактора, а в Vim нажмите Esc и наберите :wq. Теперь новые задания Cron будут добавлены и активированы. Посмотреть как выполняется ваш Cron вы можете с помощью скрипта, который я привел выше либо в лог файле. Сервис cron пишет свои логи в стандартный журнал syslog. В Ubuntu они сохраняются в файле /var/log/syslog:

cat /var/log/syslog | grep CRON

Если во время работы возникнут ошибки cron, они тоже будут здесь. Если же вам надо добавить задание Cron из какого либо скрипта, то вы всегда можете поместить свой скрипт в папку /etc/cron.d или /cron/hourly. чтобы выполнять его когда надо, только не забудьте сделать скрипт исполняемым.

Выводы

В этой статье мы разобрались как выполняется настройка cron linux на примере Ubuntu. Как видите, все только кажется сложным, но на самом деле просто если разобраться.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Get Started with Cron Jobs: Linux

Prasad Pawar

How do I add cron job under Linux or UNIX like operating system?

Cron allows Linux and Unix users to run commands or scripts at a given date and time. You can schedule scripts to be executed periodically. Cron is one of the most useful tools in a Linux or UNIX like operating systems. It is usually used for sysadmin jobs such as backups or cleaning /tmp/ directories and more. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, and /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory.

crontab command for cron jobs

You need to use the crontab command to edit/create, install, deinstall or list the cron jobs in Vixie Cron. Each user can have their own crontab file, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. You need to use crontab command for editing or setting up your own cron jobs.

Types of cron configuration files

There are different types of configuration files:

  1. The UNIX / Linux system crontab : Usually, used by system services and critical jobs that requires root like privileges. The sixth field (see below for field description) is the name of a user for the command to run as. This gives the system crontab the ability to run commands as any user.
  2. The user crontabs: User can install their own cron jobs using the crontab command. The sixth field is the command to run, and all commands run as the user who created the crontab

Note: This faq features cron implementations written by Paul Vixie and included in many Linux distributions and Unix like systems such as in the popular 4th BSD edition. The syntax is compatible with various implementations of crond.

How Do I install or create or edit my own cron jobs?

To edit or create your own crontab file, type the following command at the UNIX / Linux shell prompt:
$ crontab -e

Do I have to restart cron after changing the crontable file?

No. Cron will examine the modification time on all crontabs and reload those which have changed. Thus cron need not be restarted whenever a crontab file is modified.

Syntax of crontab (field description)

  • 1: Minute (0–59)
  • 2: Hours (0–23)
  • 3: Day (0–31)
  • 4: Month (0–12 [12 == December])
  • 5: Day of the week(0–7 [7 or 0 == sunday])
  • /path/to/command — Script or command name to schedule

Easy to remember format:

Your cron job looks as follows for system jobs:

Example: Run backup cron job script

If you wished to have a script named /root/backup.sh run every day at 3am, your crontab entry would look like as follows. First, install your cronjob by running the following command:
# crontab -e
Append the following entry:
0 3 * * * /root/backup.sh
Save and close the file.

MORE EXAMPLES

To run /path/to/command five minutes after midnight, every day, enter:
5 0 * * * /path/to/command

Run /path/to/script.sh at 2:15pm on the first of every month, enter:
15 14 1 * * /path/to/script.sh

Run /scripts/phpscript.php at 10 pm on weekdays, enter:
0 22 * * 1-5 /scripts/phpscript.php

Run /root/scripts/perl/perlscript.pl at 23 minutes after midnight, 2am, 4am …, everyday, enter:
23 0-23/2 * * * /root/scripts/perl/perlscript.pl

Run /path/to/unixcommand at 5 after 4 every Sunday, enter:
5 4 * * sun /path/to/unixcommand

How do I use operators?

An operator allows you to specify multiple values in a field. There are three operators:

  1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: “1,5,10,15,20, 25”.
  3. The dash (-) : This operator specifies a range of values, for example: “5–15” days , which is equivalent to typing “5,6,7,8,9,….,13,14,15” using the comma operator.
  4. The separator (/) : This operator specifies a step value, for example: “0–23/” can be used in the hours field to specify command execution every other hour. Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2.

How do I disable email output?

By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append >/dev/null 2>&1. For example:
0 3 * * * /root/backup.sh >/dev/null 2>&1
To mail output to particular email account let us say vivek@nixcraft.in you need to define MAILTO variable as follows:
MAILTO="vivek@nixcraft.in"
0 3 * * * /root/backup.sh >/dev/null 2>&1
See “Disable The Mail Alert By Crontab Command” for more information.

Task: List all your cron jobs

Type the following command:
# crontab -l
# crontab -u username -l
To remove or erase all crontab jobs use the following command:
# Delete the current cron jobs #
crontab -r

## Delete job for specific user. Must be run as root user ##
crontab -r -u username

What Is Crontab Syntax: Understanding Crontab on Linux + Helpful Examples

Automation is one of the key aspects of any system, whether a physical or virtual private server (VPS). If automation is set up correctly, it can save hundreds of precious hours for the user and make the overall workflow much more efficient. One of the key tools for scheduling tasks is cron.

In this tutorial, we will cover the crontab syntax, overview the differences between cron job, cron, and crontab, and provide some helpful cron jobs use cases for a Linux-based operating system.

What Is Crontab and a Cron Job?

Regarding cron jobs, three terms can be highlighted:

Cron daemon (crond) or simply cron – an executable that allows users to perform tasks and run them automatically at a specific time.

Cron job – any task a user schedules using cron is known as a cron job.

What Is Crontab Syntax?

Cron table or crontab is a file containing all schedules of the cron jobs a user wants to run regularly. Commands are written one per line and instructs the cron daemon to run a task at a specific time.

Crontab Format and Values

For the cron daemon to understand instructions correctly, the correct crontab syntax must be used. Crontab syntax consists of five fields. Each one can be filled with any of the values as shown in the following table:

How to Use Crontab: Examples of Crontab Syntax

First, use the crontab command to create your first crontab entry:

You will be asked to choose an editor. We recommend using nano, the first option in our example:

A command-line window showcasing the crontab command with an -e flag. It is used to create the main crontab file and specify the preferred editor

Afterward, you will be redirected to the crontab file. To add new entries, simply choose a new line and proceed with the cronjob.

Important! Keep in mind that crontab uses the system’s current time and date, which means that the time zone is shared with the root system.

Schedule a Job for a Specific Time

One of the simplest ways to test out cron is to schedule a job for a specific time. For example, the following cron job will execute our .sh script at the specified time, which is August 15th, at 3:30pm.

View Crontab Entries

Since all the cron jobs are stored in a crontab file, you can view the ones that are already running. To do so, use the following command to display the contents of your crontab files:

A command-line window showing the crontab -l command. All new lines to this file will create new cron jobs that will be used to execute tasks specified by the user

Edit Crontab Entries

In order to modify already existing crontab entries, use this command:

Schedule a Job for Every Minute

It is effortless to schedule tasks to run every minute. In the following example, we will instruct the cat command execution to run periodically:

A command-line window with the nano editor open. A crontab file contents can be seen, the last line is showcasing a cron job that will execute our script every minute

Schedule a Background Job Every Day

To schedule a background job to run every day, you can use the @daily cron command:

Mind that the script will be executed at 12am every day.

Schedule a Job for a Certain Range of Time

It is possible to schedule a job for a specific range of time. For example, every weekday, including weekends, from 8am to 5pm. The end result would look like this:

Here’s another example of the same cron, but just on the weekends:

Schedule a Cron Job at the Beginning of Every Month

In order to schedule a job at the beginning of every month, you can use the @monthly operator:

Keep in mind that this will execute the job at 12am on the first day of every month. Similarly, there is a @yearly operator who will run the job on the first day of every year.

Schedule a Job for More Than One Time

Users can schedule a cron job to be executed more than once, for example, five times a day. In the following example, we will set up a job to run at 12pm, 3pm, 5pm, 7pm and, 9pm.

Run a Linux Command After Each Reboot

Similarly to @daily, @monthly, and @yearly operators, bash also comes with a @reboot command. Users can use it to schedule a job that will be executed each time the system reboots or gets restarted:

Where Is the Crontab File Located?

Depending on the system’s operating system, crontab will be located at three different locations:

  • MacOS – /var/at/tabs
  • Debian-based systems – /var/spool/cron/crontabs/
  • Red Hat-based systems – /var/spool/cron

Additional Crontab Actions

Apart from the current functionality, crontab is also capable of additional actions such as creating a cron execution log or disabling email notifications. Check the sections below for more information.

Create a Log File

The easiest way to log all outputs from cron jobs is to use the following logic:

This command will save all cron jobs outputs to a file named logs.log

Disable Email

Since cron sends an email to the user after each job, disabling this functionality can be beneficial to avoid spam. Just add this line at the end of your cron job:

Crontab Environment

Crontab allows its users to define environment variables. This can be done with the aforementioned crontab -e command. When defining variables, refer to the list below:

  • PATH – default path for crontab.
  • SHELL – default shell.
  • LOGNAME – crontab owner. Information is taken from the /etc/passwd directory.
  • HOME – user’s home directory. Information is taken from the /etc/passwd directory.

Conclusion

Cron jobs are one of the best ways to perform scheduled tasks for virtual instances and physical Linux systems. With cron jobs, users can schedule various tasks for their system. For example, perform system maintenance on a particular day or even schedule it to be run every weekday.

In this tutorial, we’ve covered the majority of crontab operations. We’ve also provided some practical examples that you can use when creating a crontab.

If you have any questions or insights, feel free to leave a comment in the comments section.

Author

Ignas takes great satisfaction in helping people tackle even the most complex technical issues. His current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *