- Как запускать задания Cron каждые 5, 10 или 15 минут
- Синтаксис и операторы Crontab
- Запускать задание Cron каждые 5 минут
- Запускать задание Cron каждые 10 минут
- Запускать задание Cron каждые 15 минут
- Выводы
- Run a Cron Job Every Minute
- Basics of Crontab:
- Syntax of Running a Command Every Minute:
- Running a Crob Job Every Minute:
- Catching Errors from the Cron Jobs:
- Making Sure the Last Job Finished Running Before Running the Job Again:
- Organizing Cron Job Outputs for Easy Debugging:
- Run crontab (cron jobs) Every 10 Minutes
- How to run Cron jobs every 10, 20, or 30 minutes
- Creation of a Crontab file
- Syntax
- Run a Cron Job after every 10 minutes
- Run a Cron Job after every 20 minutes
- Run a Cron Job after every 30 minutes
- Conclusion
Как запускать задания Cron каждые 5, 10 или 15 минут
Задание cron — это задача, которая выполняется через определенные промежутки времени. Задачи можно запланировать для запуска по минуте, часу, дню месяца, месяцу, дню недели или любой их комбинации.
Задания Cron обычно используются для автоматизации обслуживания или администрирования системы, таких как резервное копирование баз данных или данных, обновление системы с использованием последних исправлений безопасности, проверка использования дискового пространства , отправка электронных писем и т. Д.
Запуск задания cron каждые 5, 10 или 15 минут — одни из наиболее часто используемых расписаний cron.
Синтаксис и операторы Crontab
Crontab (таблица cron) — это текстовый файл, определяющий расписание заданий cron. Файлы Crontab можно создавать, просматривать , изменять и удалять с помощью команды crontab .
Каждая строка в пользовательском файле crontab содержит шесть полей, разделенных пробелом, за которым следует команда, которую нужно запустить:
Первые пять полей (время и дата) также принимают следующие операторы:
- * — оператор звездочки означает все допустимые значения. Если у вас есть символ звездочки в поле Минуты, это означает, что задача будет выполняться каждую минуту.
- — — Оператор дефиса позволяет указать диапазон значений. Если вы установите 1-5 в поле «День недели», задача будет запускаться каждый будний день (с понедельника по пятницу). Диапазон является включительным, что означает, что первое и последнее значения включены в диапазон.
- , — Оператор запятой позволяет определить список значений для повторения. Например, если в поле «Час» указано 1,3,5 , задача будет выполняться в 1, 3 и 5 утра. Список может содержать отдельные значения и диапазоны, 1-5,7,8,10-15
- / — оператор косой черты позволяет указать значения шага, которые можно использовать вместе с диапазонами. Например, если в поле «Минуты» указано 1-10/2 , это означает, что действие будет выполняться каждые две минуты в диапазоне 1–10, как и при указании 1,3,5,7,9 . Вместо диапазона значений вы также можете использовать оператор звездочки. Чтобы указать задание, которое будет запускаться каждые 20 минут, вы можете использовать «* / 20».
Синтаксис общесистемных файлов crontab немного отличается от пользовательских файлов crontab. Он содержит дополнительное обязательное пользовательское поле, в котором указывается, какой пользователь будет запускать задание cron.
Чтобы отредактировать файл crontab или создать его, если он не существует, используйте команду crontab -e .
Запускать задание Cron каждые 5 минут
Есть два способа запускать задание cron каждые пять минут.
Первый вариант — использовать оператор запятой для создания списка минут:
Вышеприведенная строка синтаксически верна и будет работать нормально. Однако ввод всего списка может быть утомительным и подверженным ошибкам.
Второй вариант указать задание, которое будет запускаться каждые 5 минут часов, — это использовать оператор step:
*/5 означает создание списка всех минут и запуск задания для каждого пятого значения из списка.
Запускать задание Cron каждые 10 минут
Чтобы запускать задание cron каждые 10 минут, добавьте в файл crontab следующую строку:
Запускать задание Cron каждые 15 минут
Чтобы запускать задание cron каждые 15 минут, добавьте в файл crontab следующую строку:
Выводы
Мы показали вам, как запускать команду cron каждые 5, 10 или 15 минут.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
Run a Cron Job Every Minute
Let’s take a look at some of the real life examples of cron jobs.
- Let’s say, you own a website and you want to send all the users of your website an email every day. All you have to do is, write an email sending script and set up a cron job to run that script every day.
- Let’s say, you own an advertising agency and you want to remind all the advertisers whose balance is below 5$ to recharge. All you have to do is write a script that checks the balance of all the advertisers and when it’s below 5$, it will send a notification to the advertiser’s mobile number or email. Then set up a cron job to run the script every 5 to 10 minutes, or every hour.
There are many other usages of cron jobs in Linux.
In this article, I will show you how to run cron jobs every minute on Linux. I will be using Debian 9 Stretch for the demonstration. But you can use any modern Linux distribution of your choice. Let’s get started.
Basics of Crontab:
On Linux, you don’t have to be root in order to run cron jobs. You can run cron jobs as any user. Every user on Linux can use a crontab file to run their own set of cron jobs.
By default, a user doesn’t have a crontab file on Linux. You can create a crontab file with the following command:
If you’re running this command for the first time, then you should be asked to pick a text editor from the list. I will pick nano, the default one. You can pick the one you like. Once you’re done, press .
The crontab file should be created (if not available already) and opened with your favorite text editor. Now you can add your own cron jobs at the end of this file and once you’re happy, just save it and exit out of the text editor.
Syntax of Running a Command Every Minute:
The syntax of crontab file is as follows:
- minute can be 0 to 59.
- hour can also be 0 to 59.
- dayOfMonth can be 1 to 31.
- month can be 1 to 12.
- dayOfWeek can be 0 to 7. 0 and 7 means Sunday, 1 means Monday, 2 means Tuesday and so on.
To run a commandToRun command every minute, you should write it in the crontab file as follows:
Running a Crob Job Every Minute:
Now that we know the theories, let’s add a simple script timer.sh to the crontab file and see how to manage it.
In the timer.sh script, I only have the following lines of codes. All it does is create a new file /home/shovon/bin/timer.log (if does not exist already) and appends the output of the date command to it.
Now let’s add the script to our crontab and let it run every minute with the following line:
Once you save the crontab file and exit out of the text editor, the new crontab file should be installed.
After a minute is passed, a new file is timer.log is created in the desired directory as you can see in the marked section of the screenshot below.
From the timer.log log file, it is obvious that the script timer.sh runs every minute.
Catching Errors from the Cron Jobs:
To catch errors from a cron job, you can send the errors to a error.log file and normal outputs to access.log file for example. Of course you can name the files anything you want.
To demonstrate this, I modified my script timer.sh a little bit. Now the errors are send to error.log file in the /home/shovon/bin directory and the outputs are sent to access.log in the /home/shovon/bin directory.
At first the /tmp/i_must_be_here file does not exist, so I get the error in the error.log file as you can see.
The access.log file is empty at the moment.
Now I am going to create the file /tmp/i_must_be_here
And as you can see, the output is in the access.log file now.
If you want, you can redirect the output and the errors in the same file as follows:
As you can see, STDIN and STDERR outputs are sent to the out.log file.
Making Sure the Last Job Finished Running Before Running the Job Again:
For this to work, you can create a temporary file just after the job starts and remove it just before it finishes. Then you can check whether the temporary file exists before starting the job. If it does, you can exit out of the job and run the job only when the temporary file is unavailable.
This simple script does just that.
As you can see, the timer.pid file is created.
Reading the access.log file proves that the cron job do not run before the previous cron job finishes running. As you can see, it ran at 01:32:01 and the next time it should’ve run at 01:33:01, but it didn’t. Instead, it ran at 01:35:01, about 3 minutes later.
Organizing Cron Job Outputs for Easy Debugging:
You can format the outputs nicely to make your cron job easier to debug.
An example of how it can be done is given in the following script.
As you can see, the outputs, errors and success messages are nicely printed in the log file.
You can do amazing things with cron jobs and shell scripts. I demonstrated some of the ideas here. But the sky is your limit. Feel free to experiment with any ideas you have. Thanks for reading this article.
Источник
Run crontab (cron jobs) Every 10 Minutes
H ow do I run a cron job or a shell script every 10 minutes using Linux / UNIX cron service?
Cron> is a time-based scheduling service in a Linux or Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | None |
Est. reading time | 5m |
You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory.
First, Login to UNIX/Linux system.
Type the following command to enter cronjob:
$ crontab -e
Each cronjob has the following syntax:
- 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 ➔
To get crontab to run a task every 10 minutes you could type as follow:
*/10 * * * * /path/to/command
OR
*/10 * * * * /path/to/script
Save and close the file.
Where,
- The asterisk (*) 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.
- The */10 is used in conjunction with ranges. For example, 0-23/2 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. In this example, */10 in the minutes field to specify command execution every 10 minute.
See also
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to run Cron jobs every 10, 20, or 30 minutes
Creation of a Crontab file
Crontab shortened for Cron table file is used to run the Cron jobs. The user first must create a crontab file because it is not available by default on the system. The crontab file can be created on any Linux-based Operating system using the command given below:
If you are running the above-given command for the first time, it will first ask you to choose the text editor. Select the easiest one, “Nano Editor,” as shown in the screenshot by typing the index number of your desired editor and after selecting the editor, hit Enter:
The new crontab file will be created. Now, in this file, you can write all the Cron jobs of your choice.
Syntax
The syntax for running cronjob is that we first have to mention the time and then specify the command that we want to execute. The syntax for mentioning time is further divided into five fields.
- The first field describes the minute.
- The second field describes the hour.
- The third field describes the day of the Month.
- The fourth field describes the month.
- The fifth field describes the day of the Week.
Alright, once you have understood the right position for describing the time for running the cronjob, there are several ways as well for mentioning time.
➔ The asterisk ‘*’ operator, a.k.a wildcard, is described as all allowed values. For example, 0 0 1 * * will run the command at midnight on the first day of every month.
➔ A comma-separated list of values describes the list of values for repetition. For example, 10,20,30
➔ The dash ‘-’ operator describes the range of values. For example, 5-10.
➔ The slash ‘/’ operator helps in making the conjunction with ranges. For example, */2 * * * * will run the Cron job after every interval of 2 minutes.
Now, you have got enough theoretical knowledge about Cron jobs, let’s perform some practical stuff and see how to run Cron jobs every 10, 20, or 30 minutes.
Run a Cron Job after every 10 minutes
There can be two ways to run a Cron job after a specific interval of time, like after every 10 minutes.
The first way is to use a comma-separated list of minutes; for example, if we want to run a script after every 10 minutes, the syntax for writing such a Cron job is given below:
But isn’t it looking too tedious task to write the whole list of minutes? The slash operator helps in writing the easy syntax for running a Cron job after every 10 minutes.
In this command, */10 will create a list of minutes after every 10 minutes.
Run a Cron Job after every 20 minutes
Just like we wrote the Cron job for running the script after every 10 minutes, we can do the same for running the script after every 20 minutes:
Run a Cron Job after every 30 minutes
Similarly, the syntax for running a Cron job after every 30 minutes will be like:
Conclusion
Cron jobs are used to run the commands after a specific interval of time to manage the system updates or backing up the system’s data and we have learned how to run Cron jobs every 10, 20, or 30 minutes post. We hope this post helps in understanding and running Cron jobs.
Источник