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.
- AUR
- AUR
- AUR
- AUR
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
() can ensure that the cron job will not start a second time.
5,35 * * * * /usr/bin/flock -n /tmp/lock.backup /root/make-backup.sh
- 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.
To use an alternate default editor, define the EDITOR
environment variable in a shell initialization script as described in Environment variables.
$ su -c "crontab -e"
To have an alias to this printf
is required to carry the arbitrary string because su
launches in a new shell:
alias scron="su -c $(printf "%q " "crontab -e")"
Crontabs should never be edited directly; instead, you should use the crontab
program to work with your crontabs.
To view your crontabs:
$ crontab -l
To edit your crontabs:
$ crontab -e
To remove all of your crontabs:
$ crontab -r
If you have a saved crontab and would like to completely overwrite your old crontab:
$ crontab saved_crontab_filename
To overwrite a crontab from the command line (Wikipedia:stdin):
$ crontab -
To edit somebody else’s crontab:
# crontab -u username -e
- What is Cron?
- Introduction
- Начало работы с Cron Jobs
- Activation and autostart
- Handling errors of jobs
- Example with sSMTP
- Example with msmtp
- Example with esmtp
- Example with opensmtpd
- Long cron job
- Managing Cron Job Output
- Завершение
- Understanding How Cron Works
- Special Syntax
- Anacron
- Столкновение между Cron и Anacron
- Managing Crontabs
- Installing Cron
- Restricting Access
- Running X. org server-based applications
- Разрешения Cron
- Using run-parts and Cron Directories
- Терминология Cron Job
- How to Read a Crontab
- Scheduling Hours and Minutes with Cron
- Scheduling Days with Cron
- Using Time Shortcuts to Schedule
- Specifying Commands and Users with Cron
- Cron и PHP
- Файлы Crontab
- Анатомия записи Crontab
- Редактирование Crontab других пользователей
- Стандартные и нестандартные значения Crontab
- Диапазоны
- Списки
- Шаги
- Имена
- Предопределенные определения
- Несколько команд в одном задании Cron
- Переменные среды
- Разные часовые пояса
- Как Cron интерпретирует файлы Crontab
- Быстрое устранение неполадок
- Абсолютный путь к командам
- Убедитесь, что cron запущен
- Проверка /etc/cron.allowи /etc/cron.deny файлы
- Разрешение на выполнение
- Новый символ строки
- How Cron Works
- Перекрытия задач
- Использование Flock
- Использование механизма блокировки в скриптах
- Asynchronous job processing
- Prerequisites
- Using User Specific Crontabs
- Using Anacron with Cron
- Перенаправление вывода
- Отправьте вывод по электронной почте
- Conclusion
What is Cron?
Cron is a scheduling utility that allows you to assign tasks to run at preconfigured times. A basic tool, cron can be utilized to automate almost anything on your system that must happen at regular intervals.
In this guide, we will discuss how to use cron from the command line and how to read its configuration file. We will also explore anacron, a tool that can be used to ensure that tasks are run even when the server is turned off part of the time.
We will be using an Ubuntu 12.04 VPS, but any modern Linux distribution should operate in a similar manner.
Introduction
Cron is a time-based job scheduling daemon found in Unix-like operating systems, including Linux distributions. Cron runs in the background and operations scheduled with cron
, referred to as “cron jobs,” are executed automatically, making cron useful for automating maintenance-related tasks.
This guide provides an overview of how to schedule tasks using cron’s special syntax. It also goes over a few shortcuts you can use to expedite the process of writing job schedules and make them more understandable.
The basic format for a crontab is:
minute hour day_of_month month day_of_week command
- 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.
For example, the line:
*/5 9-16 * 1-5,9-12 1-5 ~/bin/i_love_cron.sh
will execute the script i_love_cron.sh
at five minute intervals from 9 AM to 4:55 PM on weekdays except during the months of June, July, and August.
In addition, crontab has some special keywords:
@reboot ~/bin/i_love_cron.sh
will execute the script i_love_cron.sh
at startup.
More examples and advanced configuration techniques can be found below.
/var/spool/cron/root
# Run command at a scheduled time # Edit this 'crontab -e' for error checking, man 1 crontab for acceptable format # <@freq> <tags and command> @hourly ID=sys-hourly /usr/sbin/run-cron /etc/cron.hourly @daily ID=sys-daily /usr/sbin/run-cron /etc/cron.daily @weekly ID=sys-weekly /usr/sbin/run-cron /etc/cron.weekly @monthly ID=sys-monthly /usr/sbin/run-cron /etc/cron.monthly # mm hh DD MM W /path/command (or tags) # W = week: 0-6, Sun=0 21 01 * * * /usr/bin/systemctl suspend
These lines exemplify one of the formats that crontab entries can have, namely whitespace-separated fields specifying:
- @period
- ID=jobname (this tag is specific to dcron)
- command
The other standard format for crontab entries is:
- minute
- hour
- day
- month
- day of week
- command
See the crontab man page for further information and configuration examples.
Начало работы с Cron Jobs
Если мы заглянем внутрь /etc
каталога, то увидим такие каталоги, как cron.hourly
, cron.daily
, cron.weekly
и cron.monthly
, каждый из которых соответствует определенной частоте выполнения.
Одним из способов планирования наших задач является размещение наших сценариев в соответствующем каталоге. Например, для db_backup.php
ежедневного запуска мы поместили его внутрь cron.daily
. Если папка для данной частоты отсутствует, нам нужно будет сначала создать ее.
Этот подход использует run-parts
скрипт, команду, которая запускает каждый исполняемый файл, который он находит в указанном каталоге.
Это самый простой способ запланировать задачу. Однако, если нам нужна большая гибкость, мы должны использовать Crontab.
Вам нужно регулярно запускать скрипт, но вы не хотите запускать его вручную? Или, может быть, вам нужно выполнить команду в определенное время или интервал, но вы не хотите, чтобы процесс монополизировал ваш процессор или память. В любом случае cron jobs идеально подходят для этой задачи. Давайте посмотрим, что это такое, как их настроить и что с ними можно сделать.
Бывают случаи, когда в будущем необходимо автоматически запускать группу задач в определенное время. Эти задачи обычно являются административными, но могут быть любыми – от создания резервных копий базы данных до загрузки электронных писем, когда все спят.
Cron — это планировщик заданий на основе времени в Unix-подобных операционных системах, который запускает определенные задачи в будущем. Название происходит от греческого слова χρόνος (хронос), что означает время.
Наиболее часто используемая версия Cron известна как Vixie Cron. Пол Викси первоначально разработал его в 1987 году.
01 * * * * /bin/echo Hello, world!
*/5 * * jan mon-fri /bin/echo Hello, world!
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 ):
*0,*5 9-16 * 1-5,9-12 1-5 /home/user/bin/i_love_cron.sh
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:
# Chronological table of program loadings # Edit with "crontab" for proper functionality, "man 5 crontab" for formatting # User: johndoe # mm hh DD MM W /path/progam [--option]... ( W = weekday: 0-6 [Sun=0] ) 21 01 * * * /usr/bin/systemctl hibernate @weekly $HOME/.local/bin/trash-empty
Here are some self-explanatory crontab syntax examples:
30 4 echo "It is now 4:30 am." 0 22 echo "It is now 10 pm." 30 15 25 12 echo "It is 3:30pm on Christmas Day." 30 3 * * * echo "Remind me that it's 3:30am every day." 0 * * * * echo "It is the start of a new hour." 0 6 1,15 * * echo "At 6am on the 1st and 15th of every month." 0 6 * * 2,3,5 echo "At 6am on Tuesday, Wednesday and Thursdays." 59 23 * * 1-5 echo "Just before midnight on weekdays." 0 */2 * * * echo "Every two hours." 0 20 * * 4 echo "8pm on a Thursday." 0 20 * * Thu echo "8pm on a Thursday." */15 9-17 * * 2-5 echo "Every 15 minutes from 9am-5pm on weekdays." @yearly echo "Happy New Year!"
To see it just type
crontab -l
and, yes you’ve seen it right, when you want to add a crontab
then simply do
crontab -e
for the first time you’ll be asked about the editor to use with crontab
. As you are a newbie as you say, I’d recommend to use nano, it’s the simplest editor to use.
The crontab itself works like this
MIN = Minute 0-60
HOUR = Hour [24-hour clock] 0-23
MDAY = Day of Month 1-31
MON = Month 1-12 OR jan,feb,mar,apr ...
DOW = Day of Week 0-6 OR sun,mon,tue,wed,thu,fri,sat
COMMAND = Command to be run Any valid command-line
So e.g. to trigger a job every 15 minutes only on monday, you do it like so
*/15 * * * mon /home/me/yourscript.sh
Also very important!
cronjob is dumb! Yes I said it. Always make sure to enter the full PATH to the application/command/script
you are using, because crontab won’t work with .bashrc
or similar. You always have to make sure that you tell cron where it can find the files and directories.
To answer the rest of your questions:
Of course it will run on it’s own, that’s what it’s there for. But you need to check that cronjob really does it, or if it’s missing something. E.g. log into a logfile to see if it really works.
And NO, a restart is not needed. A restart with linux is normally only needed, if you install a new kernel. For it to use you’d need to reboot. Almost everything else can be done without reboot in Linux. Of course there are exceptions, but in general this statement is correct.
/etc/ |----- cron.d/ | ----- 0hourly |----- cron.minutely/ |----- cron.hourly/ | ----- 0anacron |----- anacrontab |----- cron.daily/ |----- cron.monthly/ |----- cron.weekly/ |----- crontab |----- cron.deny
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.
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.
- Cronie uses
run-parts
to carry out scripts in the different directories. The filenames should not include any dot (.) sincerun-parts
in its default mode will silently ignore them (see ). The names must consist only of upper and lower-case letters, digits, underscores and minus-hyphens. - The output of
systemctl status cronie
might show a message such asCAN'T OPEN (/etc/crontab): No such file or directory
. However, this can be ignored since cronie does not require one. - Cronie is particular about the permissions for
/etc/cron.d/0hourly
. None of the tasks in/etc/cron.d/{hourly,weekly,daily} ... etc
will be run (including the anacron launcher) if/etc/cron.d/0hourly
is damaged or has improper permissions.pacman -Qkk cronie
can show if you have any such issues.
Tip: To prevent the sending of output and stop email alert, add >/dev/null 2>&1
at the end of the line for each cron job to redirect output to /dev/null.
0 1 5 10 * /path/to/script.sh >/dev/null 2>&1
You can also set MAILTO=””
variable in your crontab file to disable email alerts.
I tried to set up a root cron job to run a Bash script as root, to run at minute 7,37, every hour, every day of month, every month. This script is located in /usr/bin
and named tunlrupdate.sh
. It updates the DNS of Tunlr.
$ ls -l /usr/bin/tunlrupdate.sh
-rwxr-xr-x 1 root root 2133 Sep 24 15:42 /usr/bin/tunlrupdate.sh
This Bash script is available here.
When invoked the script writes what’s happening in a log located in /var/log/tunlr.log
To add this root cron job I used the standard for root’s crontab
sudo crontab -e
And inserted these 2 lines at the end. I expect cron to run the script as root.
# check for updated Tunlr DNS every 30 minutes at the hour + 7 mn and hour + 37 mn
07,37 * * * * root /usr/bin/tunlrupdate.sh
A later command sudo crontab -l
confirmed that the cron job has been inserted.
I did reboot Ubuntu and was checking in the log file if the cron job was launched properly. However there is nothing in the logfile /var/log/tunlr.log
meaning the job was never successfully launched.
I did check that if I run the script from the command line
sudo /usr/bin/tunlrupdate.sh
then the logfile is updated accordingly.
Why is this cron job not running as planned in my system?
UPDATE 1 : All the proposed solutions so far do not work. I thank Olli for a CLI to list the system log sudo grep CRON /var/log/syslog
. However I did get a CRON error
CRON[13092]: (root) CMD ( [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ]
&& find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php
/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
with the suggested PATH= insertion & use of absolute path from root for functions in the script or without this suggested solutions here. I still get this error.
After some searching I pinpointed the error in the file /usr/lib/php5/maxlifetime
as is explained here: Change #!/bin/sh -e --> #!/bin/sh -x
Then listing the CRON error log in my system
sudo grep CRON /var/log/syslog
Feb 11 18:07:01 Marius-PC CRON[14067]: (root) CMD (root /usr/bin/tunlrupdate.sh)
Feb 11 18:07:01 Marius-PC CRON[14066]: (root) MAIL (mailed 1 byte of output; but got
status 0x00ff, #012)
#!/bin/bash
LOGFILE=/var/log/tunlr.log
echo $LOGFILE >> $LOGFILE
I still don’t get the cron job through. Nothing is written in the log file. So even may be an empty script will not run in cron ? I don’t get it. I am know trying a script reduced to these 2 lines:
#!/bin/bash
exit 0
I want to schedule a task to run on a regular basis and have heard that Cron is the way to do this.
How do I add Cron jobs in Ubuntu?
117 gold badges677 silver badges834 bronze badges
asked Aug 16, 2010 at 8:25
Gabriel Solomon
5 gold badges24 silver badges22 bronze badges
Put a shell script in one of these folders: /etc/cron.daily
, /etc/cron.hourly
, /etc/cron.monthly
or /etc/cron.weekly
.
If these are not enough for you, you can add more specific tasks e.g. twice a month or every 5 minutes. Go to the terminal and type:
crontab -e
This will open your personal crontab (cron configuration file). The first line in that file explains it all! In every line you can define one command to run and its schedule, and the format is quite simple when you get the hang of it. The structure is:
minute hour day-of-month month day-of-week command
For all the numbers you can use lists, e.g. 5,34,55
in the minutes field will mean run at 5 past, 34 past, and 55 past whatever hour is defined.
You can also use intervals. They are defined like this: */20
. This example means every 20th, so in the minutes column it is equivalent to 0,20,40
.
So to run a command every Monday at 5:30 in the afternoon:
30 17 * * 1 /path/to/command
or every 15 minutes
*/15 * * * * /path/to/command
Note that the day-of-week goes from 0-6 where 0 is Sunday.
If you want to run something every 10 minutes, for example, you add a line like this
*/10 * * * * /usr/bin/somedirectory/somecommand
and save the file.
To add a cron job that runs as root, you can edit root’s crontab by running sudo crontab -e
.
For example, if you want to run something every 10 minutes as root, you’d add a line like this
*/10 * * * * root /usr/bin/somedirectory/somecommand
You can see the contents of the system crontab file with cat /etc/crontab
.
More details at: https://help.ubuntu.com/community/CronHowto
56 gold badges215 silver badges327 bronze badges
answered Aug 16, 2010 at 8:58
If you prefer to do it using a GUI, you can go to the Software Center and install Scheduled tasks (or run sudo apt-get install gnome-schedule
). It will provide a powerful GUI to add cron tasks.
22 gold badges120 silver badges212 bronze badges
answered Aug 16, 2010 at 9:21
Javier Rivera
11 gold badges87 silver badges110 bronze badges
I recommend KDE’s Task Scheduler (kde-config-cron
) . Access it from the System Settings in the Task Scheduler module there.
It manages both personal and system Crontabs, and the ease of creating the time boundaries greatly surprised me (see the screenshot below). I think this part is really underrated.
answered Jan 31, 2013 at 23:59
33 gold badges187 silver badges282 bronze badges
I wanted to set a Cron job to run through a bash script, so executing the script would add a cron job.
I realised that when you make use of:
crontab -e
Then it creates the file:
echo "30 17 * * 1 /path/to/command" > /var/spool/cron/crontabs/root
We also need to set the correct ownership for the file:
chown root:root /var/spool/cron/crontabs/root
And set the correct permissions:
chmod 600 /var/spool/cron/crontabs/root
echo "30 17 * * 1 /path/to/command" >> /var/spool/cron/crontabs/root
answered Sep 27, 2016 at 20:25
KDE Task Scheduler will not work in regular Ubuntu. It works only in KDE Systems like KUbuntu. For non KDE system you will prefer to use gnome-schedule
$ sudo apt-get install gnome-schedule
The app is Scheduled tasks in the Dash.
answered Feb 11, 2014 at 14:35
2 gold badges14 silver badges24 bronze badges
Example of running script test_cron.sh
by cron every minute on Ubuntu 18.04 using symbolic link:
#!/bin/bash
echo "System backuped" >> /media/myname/data/backup/backup_tmp.log
sudo nano /etc/cron.allow
root
myname
The path to script is /home/myname/shell/test_cron.sh
I changed the owner and made it executable:
sudo chown myname /home/myname/shell/test_cron.sh
chmod +x /home/myname/shell/test_cron.sh
I added symbolic link:
sudo ln -s /home/myname/shell/test_cron.sh /usr/bin/test_cron
Logged as myname
I added new task to execute test_cron
every minute.
crontab -e
*/1 * * * * test_cron
To check if the command in the list:
crontab -l
*/1 * * * * test_cron
To check execution
grep -i cron /var/log/syslog
Nov 17 12:28:01 myname-ubuntu CRON[13947]: (myname) CMD (system-backup)
answered Nov 17, 2018 at 9:41
answered Apr 7, 2020 at 18:59
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.
Note: cronie provides the 0anacron
hourly job, which allows for delayed runs of other jobs e.g. if the computer was switched off at the moment of standard execution.
Handling errors of jobs
- Edit the
cronie.service
unit. - Install AUR, msmtp, , 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 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.service
to insure that it detects that you now have a /usr/bin/sendmail
installed.
Example with msmtp
Then either add MAILTO
line to your crontab, like so:
MAILTO=your@email.com
or create /etc/msmtprc
and append this line:
aliases /etc/aliases
and create /etc/aliases
:
your_username: your@email.com # Optional: default: your@email.com
Then modify the configuration of cronie daemon by replacing the ExecStart
command with:
ExecStart=/usr/bin/crond -n -m '/usr/bin/msmtp -t'
Example with esmtp
Install AUR and AUR.
After installation configure the routing:
/etc/esmtprc
identity myself@myisp.com hostname mail.myisp.com:25 username "myself" password "secret" starttls enabled default mda "/usr/bin/procmail -d %T"
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:
$ sendmail user_name < message.txt
$ cat /var/spool/mail/user_name
You should now see the test message and the time and date it was sent.
/etc/esmtprc
force_mda="user-name"
Note: If the above test did not work, you may try creating a local configuration in ~/.esmtprc
with the same content.
$ chmod 710 ~/.esmtprc
Then repeat the test with message.txt
exactly as before.
Example with opensmtpd
listen on localhost action "local" mbox alias <aliases> match for local action "local"
You can proceed to test it. First start smtpd.service
. Then do:
$ echo test | sendmail user
This approach has the advantage of not sending local cron notifications to a remote server. On the downside, you need a new daemon running.
- At the moment of writing the Arch opensmtpd package does not create all needed directories under
/var/spool/smtpd
, but the daemon will warn about that specifying the required ownerships and permissions. Just create them as suggested. - Even though the suggested configuration does not accept remote connections, it is a healthy precaution to add an additional layer of security blocking port 25 with iptables or similar.
Long cron job
Suppose this program is invoked by cron :
#!/bin/sh echo "I had a recoverable error!" sleep 1h
What happens is this:
- cron runs the script
- 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.
- the MTA opens the connection to postfix and leaves that connection open while it waits for the rest of the body.
- postfix closes the idle connection after less than an hour and you get an error like this :
smtpmsg='421 … Error: timeout exceeded' errormsg='the server did not accept the mail'
To solve this problem you can use the command chronic or sponge from .
From their respective man page:
- 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 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.
Managing Cron Job Output
Because cron
jobs are executed in the background, it isn’t always apparent that they’ve run successfully. Now that you know how to use the crontab
command and how to schedule a cron
job, you can start experimenting with some different ways of redirecting the output of cron
jobs to help you track that they’ve been executed successfully.
. . .
MAILTO="example@digitalocean.com"
SHELL=/bin/bash
HOME=/
* * * * * echo ‘Run this command every minute’
This particular job will return “Run this command every minute,” and that output will get emailed every minute to the email address specified after the MAILTO
directive.
You can also redirect a cron
task’s output into a log file or into an empty location to prevent getting an email with the output.
* * * * * echo ‘Run this command every minute’ >> /directory/path/file.log
* * * * * /usr/bin/php /var/www/domain.com/backup.php > /dev/null 2>&1
This cron
job also redirects standard error — represented by 2
— to standard output (>&1
). Because standard output is already being redirected to /dev/null
, this essentially allows the script to run silently. Even if the crontab
contains a MAILTO
statement, the command’s output won’t be sent to the specified email address.
Завершение
Cron — это , выполняющий список событий, запланированных на будущее. Мы определяем эти задания в специальных файлах конфигурации, называемых файлами crontab. Пользователи могут иметь свой собственный файл crontab, если им разрешено использовать Cron на основе /etc/cron.allow
или /etc/cron.deny files
. В дополнение к заданиям cron на уровне пользователя Cron также загружает общесистемные задания cron, которые немного отличаются по синтаксису.
Наши задачи обычно PHP скрипты или утилиты командной строки. В системах, которые не работают все время, мы можем использовать Anacron для запуска событий, которые происходят в течение n
нескольких дней.
При работе с Cron мы также должны знать о задачах, перекрывающих друг друга, чтобы предотвратить потерю данных. После завершения задания cron выходные данные будут отправлены владельцу crontab и/или электронной почты, указанной в переменной MAILTO
среды.
Understanding How Cron Works
To schedule a job, open up your crontab
for editing and add a task written in the form of a cron expression. The syntax for cron expressions can be broken down into two elements: the schedule and the command to run.
minute hour day_of_month month day_of_week command_to_run
Here’s a functional example of a cron expression. This expression runs the command curl http://www.google.com
every Tuesday at 5:30 PM:
30 17 * * 2 curl http://www.google.com
There are also a few special characters you can include in the schedule component of a cron expression to streamline scheduling tasks:
*
: In cron expressions, an asterisk is a wildcard variable that represents “all.” Thus, a task scheduled with* * * * * ...
will run every minute of every hour of every day of every month.,
: Commas break up scheduling values to form a list. If you want to have a task run at the beginning and middle of every hour, rather than writing out two separate tasks (e.g.,0 * * * * ...
and30 * * * * ...
), you could achieve the same functionality with one (0,30 * * * * ...
).-
: A hyphen represents a range of values in the schedule field. Instead of having 30 separate scheduled tasks for a command you want to run for the first 30 minutes of every hour (as in0 * * * * ...
,1 * * * * ...
,2 * * * * ...
, and so on), instead, you could schedule it as0-29 * * * * ...
./
: You can use a forward slash with an asterisk to express a step value. For example, instead of writing out eight separate separatecron
tasks to run a command every three hours (as in,0 0 * * * ...
,0 3 * * * ...
,0 6 * * * ...
, and so on), you could schedule it to run like this:0 */3 * * * ...
.
Here are some more examples of how to use cron’s scheduling component:
* * * * *
— Run the command every minute.12 * * * *
— Run the command 12 minutes after every hour.0,15,30,45 * * * *
— Run the command every 15 minutes.*/15 * * * *
— Run the command every 15 minutes.0 4 * * *
— Run the command every day at 4:00 AM.0 4 * * 2-4
— Run the command every Tuesday, Wednesday, and Thursday at 4:00 AM.20,40 */8 * 7-12 *
— Run the command on the 20th and 40th minute of every 8th hour every day of the last 6 months of the year.
If you find any of this confusing or if you’d like help writing schedules for your own cron
tasks, Cronitor provides a handy cron
schedule expression editor named “Crontab Guru” which you can use to check whether your cron
schedules are valid.
Special Syntax
There are also several shorthand commands you can use in your crontab
file to help streamline job scheduling. They are essentially shortcuts for the equivalent numeric schedule specified:
Note: Not all cron
daemons can parse this syntax (particularly older versions), so double-check it works before you rely on it.
@reboot echo "System start up"
Using these shortcuts whenever possible can help make it easier to interpret the schedule of tasks in your crontab
.
Anacron
Одна из проблем с Cron заключается в том, что он предполагает, что система работает непрерывно (24 часа в сутки). Это вызывает проблемы для машин, которые не работают весь день (например, персональные компьютеры). Если система отключается в течение запланированного времени выполнения задачи, Cron не будет выполнять эту задачу задним числом.
Anacron не является заменой Cron, но решает эту проблему. Он выполняет команды один раз в день, неделю или месяц, но не поминутно или ежечасно, как это делает Cron. Однако это гарантия того, что задача будет выполнена, даже если система отключится на непредвиденный период времени.
Только root или пользователь с правами администратора может управлять задачами Anacron. Anacron не работает в фоновом режиме, как , а только один раз, выполняя задачи, которые должны быть выполнены.
Anacron использует файл конфигурации (так же, как crontab) с именем anacrontabs
. Этот файл находится в /etc
каталоге.
Содержимое этого файла выглядит следующим образом:
# /etc/anacrontab: configuration file for anacron
# See anacron(8) and anacrontab(5) for details.
/bin/sh
/sbin:/bin:/usr/sbin:/usr/bin
root
# the maximal random delay added to the base delay of the jobs
-22
#period in days delay in minutes job-identifier command
cron.daily run-parts /etc/cron.daily
cron.weekly run-parts /etc/cron.weekly
@monthly cron.monthly run-parts /etc/cron.monthly
В anacrontab
файле мы можем установить частоты только с периодом n
дней, за которым следует время задержки в минутах. Это время задержки просто для того, чтобы убедиться, что задачи не выполняются одновременно.
Третий столбец — это уникальное имя, которое идентифицирует задачу в файлах журнала Anacron.
Четвертый столбец — это фактическая команда для запуска.
Рассмотрим следующую запись:
cron.daily run-parts /etc/cron.daily
Эти задачи выполняются ежедневно, через пять минут после запуска Anacron. Он использует run-parts
для выполнения всех скриптов внутри/etc/cron.daily
.
Вторая запись в списке выше выполняется каждые 7 дней (еженедельно) с задержкой 25 минут.
Столкновение между Cron и Anacron
Как вы, наверное, заметили, Cron также настроен на выполнение скриптов внутри /etc/cron.*
каталогов. Различные варианты Linux обрабатывают такое возможное столкновение с Anacron по-разному. В Ubuntu Cron проверяет, присутствует ли Anacron в системе, и если это так, он не будет выполнять сценарии в /etc/cron.*
каталогах.
В других версиях Linux Cron обновляет временные метки Anacron при выполнении задач. Anacron не будет выполнять их, если Cron уже запустил их.
Managing Crontabs
Once you’ve settled on a schedule and you know the job you want to run, you’ll need to put it somewhere your daemon will be able to read it.
-
no crontab for sammy - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- easiest
2. /usr/bin/vim.basic
3. /usr/bin/vim.tiny
4. /bin/ed
Choose 1-4 [1]:
Enter the number corresponding to the editor of your choice. Alternatively, you could press ENTER
to accept the default choice, nano
.
After making your selection, you’ll be taken to a new crontab
containing some commented-out instructions on how to use it:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
When you run crontab -e
in the future, it will bring up your crontab
in this text editor automatically. Once in the editor, you can input your schedule with each job on a new line. Otherwise, you can save and close the crontab for now (CTRL + X
, Y
, then ENTER
if you selected nano
).
- /etc/crontab
-
-
-
crontab: really delete sammy's crontab? (y/n)
When prompted, you must enter y
to delete the crontab
or n
to cancel the deletion.
Installing Cron
Almost every Linux distribution has some form of cron
installed by default. However, if you’re using an Ubuntu machine on which cron
isn’t installed, you can install it using APT.
Before installing cron
on an Ubuntu machine, update the computer’s local package index:
- update
-
You’ll need to make sure it’s set to run in the background too:
- systemctl
Synchronizing state of cron.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable cron
Restricting Access
- ALL /etc/cron.deny
- ishmael /etc/cron.allow
- user
The user user cannot use this program (crontab)
Running X. org server-based applications
17 02 * ... /usr/bin/xuserrun /usr/bin/xclock
17 02 * ... env DISPLAY=:0 /usr/bin/xclock
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:
17 02 * ... env DBUS_SESSION_BUS_ADDRESS=your-address notify-send 'Foo bar'
If done through say SSH, permission will need be given:
# xhost +si:localuser:$(whoami)
Разрешения Cron
Мы можем указать, какой пользователь должен иметь возможность использовать Cron, а какой нет. Есть два файла, которые играют важную роль, когда дело доходит до разрешений cron: /etc/cron.allow
и /etc/cron.deny
.
Если /etc/cron.allow
существует, то наше имя пользователя должно быть указано в этом файле для использования crontab
. Если /etc/cron.deny
существует, он не должен содержать наше имя пользователя. Если ни один из этих файлов не существует, то на основе параметров конфигурации, зависящих от сайта, либо , либо смогут использовать crontab
команду. Например, в Ubuntu, если ни один файл не существует, все пользователи могут использовать crontab по умолчанию.
Мы можем поместить ALL
/etc/cron.deny
файл, чтобы запретить всем пользователям использовать cron:
ALL /etc/cron.deny
Примечание: Если мы создаем /etc/cron.allow
файл, нет необходимости создавать /etc/cron.deny
файл, поскольку он имеет тот же эффект, что и создание /etc/cron.deny
файла с ALL
в нем.
Using run-parts and Cron Directories
If you look at the commands specified in the system crontab, you will see a mention of «anacron», which we will discuss later, and «run-parts».
The run-parts command is a simple command that runs every executable located within a specified directory. It is used extensively with cron because it allows you to run multiple scripts at a specified time by placing them in a single location.
This has the advantage of allowing the crontab to be kept clean and simple, and allowing you to add additional scripts by simply placing them in or linking them to the appropriate directory instead of adjusting the crontab.
By default, most distributions set up folders for each interval, where they place the scripts or links to the scripts that they would like to run at that interval.
For instance, Ubuntu has folders named «cron.daily», «cron.hourly», «cron.monthly», and «cron.weekly». Inside of these folders are the appropriate scripts.
Терминология Cron Job
- Job: единица работы, серия шагов, чтобы что-то сделать. Например, отправка электронной почты группе пользователей. В этой статье будет использоваться задачазаданиеcron или событие взаимозаменяемо.
- Daemon: компьютерная программа, которая работает в фоновом режиме, служа различным целям. часто запускаются во время загрузки. Веб-сервер — это демон, обслуживающий HTTP-запросы. Cron — это для выполнения запланированных задач.
- Cron Job: задание cron — это запланированное задание задание, когда оно должно быть выполнено.
- Webcron планировщик заданий на основе времени, который работает в серверной среде. Это альтернатива стандартному Cron, часто на общих веб-хостах, которые не предоставляют доступ к оболочке.
How to Read a Crontab
Cron decides which commands to run at what time by reading a series of files, each known as a «crontab». We can see the system-wide crontab by looking at «/etc/crontab»:
less /etc/crontab
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
This is the system crontab and should not be edited in most cases. Most of the time it is preferable to use your own crontab. The system file could be replaced in an update and your changes would be lost.
The file has a few interesting parts that we need to understand.
The first two lines specify the shell that will execute the commands listed and the path to check for the programs.
The rest of the file specifies the actual commands and scheduling. The lines in this list each represent a record, or row, in a table. The «tab» in «crontab» stands for table. Each table cell is represented by a column separated by spaces or tabs.
The commented line above the table gives a hint as to what each of the columns represent:
# m h dom mon dow user command
Scheduling Hours and Minutes with Cron
The first column is the minute (0-59) of the hour that the command should run. The second column is the hour of the day, from 0-23, that it should run. An asterisk (*) means «every possible value», and is used as a wildcard.
By combining these first two columns, we can get a time value for the command. For instance, the second line in the table has 25 in the minutes column and 6 in the hours column:
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
This means the second line should be run at 6:25 in the morning.
Similarly, the first line means that the command should be run every hour, at 17 minutes passed the hour:
17 * * * * root cd / && run-parts --report /etc/cron.hourly
So it will be run at 1:17am, 2:17am, 3:17am, etc.
Scheduling Days with Cron
The third, fourth, and fifth column determine which days the command should be run. The third column specifies a day of the month, 1-31 (be careful when scheduling for late in the month, as not all months have the same number of days).
The fourth column specifies which months, from 1-12, a command should be run, and the fifth column is reserved to specify which day of the week a command should be run, with 0 and 7 both meaning Sunday. This last one allows you to schedule by week instead of by month.
If both the day of the week and the day of the month columns have values that are not wildcards, then the command will execute if either of the columns match.
Days of the week and months can also be specified with the first three letters of their name. We can also use ranges with hyphens (-) and select multiple values with commas (,).
If we look at the crontab, you will see that the third record is run every Sunday at 6:47am:
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
The fourth record is run on the first of the month at 6:52am:
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
Using Time Shortcuts to Schedule
Keep in mind that these shortcuts do not provide fine-grained control over when they are run. They are also all configured to run at the first possible moment of the matching time.
Specifying Commands and Users with Cron
The next columns involve the actual execution of the commands scheduled.
The final column specifies the actual command that should be executed. The command can contain a percent sign (%), which means that everything beyond the first percent sign is passed to the command as standard input.
Every record needs to end with a new-line character. This is not a problem for most entries, but be sure that you have a blank line after the final entry, or else the command will not run properly.
Cron и PHP
Обычно мы запускаем наши скрипты командной строки PHP, используя исполняемый файл PHP.
php script.php
В качестве альтернативы мы можем использовать shebang в начале скрипта и указать на исполняемый файл PHP:
?php
// PHP code here
В результате мы можем выполнить файл, вызвав его по имени. Тем не менее, мы должны убедиться, что у нас есть разрешение на его выполнение.
Чтобы иметь более надежные скрипты командной строки PHP, мы можем использовать сторонние компоненты для создания консольных приложений, таких как Symfony Console Component или Laravel Artisan. Эта статья является хорошим началом для использования консольного компонента Symfony.
Файлы Crontab
Cron использует специальные файлы конфигурации, называемые crontab
файлами, которые содержат список выполняемых заданий. Crontab означает . Каждая строка в файле crontab называется заданием cron, которое напоминает набор столбцов, разделенных символом пробела. Каждая строка указывает и Cron должен выполнять определенную команду или сценарий.
В файле crontab пустые строки или строки, начинающиеся с #
пробелов или табуляции, будут игнорироваться. Строки, начинающиеся с #, считаются комментариями.
Ниже приведен пример файла crontab с одной записью:
* * * /var/www/sites/db_backup.sh
Первая часть 0 0 * * *
— это выражение cron, которое определяет частоту выполнения. Вышеуказанное задание cron будет выполняться один раз в день.
Пользователи могут иметь свои собственные файлы crontab, названные в честь их имени пользователя, зарегистрированного в /etc/passwd
файле. Все файлы crontab пользовательского уровня находятся в области spool Cron. Вы не должны редактировать эти файлы напрямую. Вместо этого мы должны редактировать их с помощью утилиты crontab
командной строки.
Примечание: Каталог spool варьируется в разных дистрибутивах Linux. На Ubuntu это /var/spool/cron/crontabs
в то время как в CentOS это /var/spool/cron
.
Чтобы отредактировать наш файл crontab:
-e
Приведенная выше команда автоматически откроет файл crontab, принадлежащий нашему пользователю. Если вы еще не выбрали редактор по умолчанию для crontab, вы увидите набор установленных редакторов для выбора. Мы также можем явно выбрать или изменить нужный нам редактор для редактирования файла crontab:
nano -e
После сохранения файла и выхода из редактора crontab будет проверен на точность. Если все настроено правильно, файл будет сохранен в каталоге spool.
Каждая команда в файле crontab выполняется с точки зрения пользователя, которому принадлежит crontab. Если ваша команда выполняется как root (sudo), вы не сможете определить этот crontab из своей учетной записи пользователя, если вы не войдете в систему как root.
Список установленных cron jobs, принадлежащих нашему пользователю:
-l
Мы также можем записать наши задания cron в файл и отправить его содержимое в файл crontab следующим образом:
/path/to/the/file/containing/cronjobs.txt
Предыдущая команда перезапишет существующий файл crontab /path/to/the/file/containing/cronjobs.txt
.
Чтобы удалить crontab, мы используем -r
опцию:
-r
Анатомия записи Crontab
Анатомия записи crontab на уровне пользователя выглядит следующим образом:
# ┌───────────── min (0 - 59)
# │ ┌────────────── hour (0 - 23)
# │ │ ┌─────────────── day of month (1 - 31)
# │ │ │ ┌──────────────── month (1 - 12)
# │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute
В первых двух полях указывается время ( и ), в которое будет выполняться задача. Следующие два поля указывают и . Пятое поле указывает .
Cron выполнит команду, когда минута, час, месяц и или совпадут с текущим временем.
Если и имеют определенные значения, событие будет выполняться, когда поле соответствует текущему времени. Рассмотрим следующее выражение:
-20/5 Feb /path/to/command
Предыдущее задание cron будет выполняться один раз в день каждые пять дней, с 5 по 20 февраля все вторники февраля.
Важно: Когда и день месяца, и день недели имеют определенные значения (не звездочку), он создаст OR
условие, то есть оба дня будут совпадать.
Синтаксис в system crontabs (/etc/crontab
) немного отличается от crontabs пользовательского уровня. Разница в том, что шестое поле — это команда, а , от имени которого мы хотим запустить задание.
* * * * * testuser /path/to/command
Не рекомендуется помещать общесистемные задания cron /etc/crontab
, так как этот файл может быть изменен в будущих обновлениях системы. Вместо этого мы помещаем эти задания cron в /etc/cron.d
каталог.
Редактирование Crontab других пользователей
Возможно, нам придется редактировать файлы crontab других пользователей. Для этого мы используем -u
опцию, как показано ниже:
-u username -e
Примечание Мы можем редактировать файлы crontab других пользователей только как пользователь root или как пользователь с правами администратора.
Некоторые задачи требуют прав администратора. Вы должны добавить их в файл crontab корневого пользователя:
-e
Обратите внимание, что использование sudo
with crontab -e
будет редактировать файл crontab корневого пользователя. Если нам нужно отредактировать crontab другого пользователя во время использования sudo
, мы должны использовать -u
опцию для указания владельца crontab.
Стандартные и нестандартные значения Crontab
Поля Crontab принимают числа в качестве значений. Однако мы можем поместить в эти поля и другие структуры данных.
Диапазоны
Мы можем передавать диапазоны чисел:
-18 -15 * * /path/to/command
Вышеуказанное задание cron будет выполняться с 6 утра до 6 вечера с 1-го по 15-е число каждого месяца в году. Обратите внимание, что указанный диапазон включен, поэтому 1-5 означает 1,2,3,4,5.
Списки
Список — это группа значений, разделенных запятыми. Мы можем иметь списки в качестве значений полей:
,5,7 * * * /path/to/command
Приведенный выше синтаксис будет запускать задание cron в 1 am, 4 am, 5 am и 7 am каждый день.
Шаги
Шаги можно использовать с диапазонами или символом звездочки(*)
. Когда они используются с диапазонами, они указывают количество значений, которые нужно через конец диапазона. Они определяются «/"
символом после диапазона, за которым следует число. Рассмотрим следующий синтаксис:
-18/2 * * * /path/to/command
Вышеуказанное задание cron будет выполняться каждые два часа с 6 утра до 6 вечера.
Когда шаги используются со звездочкой, они просто указывают частоту этого конкретного поля. Например, если мы устанавливаем минуту*/5
, это просто означает каждые пять минут.
Мы можем комбинировать списки, диапазоны и шаги вместе, чтобы иметь более гибкое планирование событий:
-10/5,14,15,18-23/3 * /path/to/command
Вышеуказанное событие будет проходить каждые пять часов с полуночи 1 января до 10 утра, 2 вечера, 3 вечера, а также каждые три часа с 6 вечера до 11 вечера.
Имена
Для полей и мы можем использовать первые три буквы определенного дня или месяца, например Sat
, sun
, Feb
, Sep
, и т.д.
* * * Feb,mar sat,sun /path/to/command
Предыдущее задание cron будет выполняться только по субботам и воскресеньям февраля и марта.
Обратите внимание, что имена чувствительны к регистру. Диапазоны не допускаются при использовании имен.
Предопределенные определения
Некоторые реализации cron могут поддерживать некоторые специальные строки. Эти строки используются вместо первых пяти полей, каждое из которых определяет определенную частоту:
- annual Запуск один раз в год в полночь 1 января
(0 0 1 1 *)
- запуск один раз в месяц, в полночь первого дня месяца
(0 0 1 * *)
- запуск один раз в неделю в полночь воскресенья
(0 0 * * 0)
- запуск один раз в день в полночь
(0 0 * * *)
- запуск в начале каждого часа
(0 * * * *)
- Запуск один раз при запуске
Несколько команд в одном задании Cron
Мы можем выполнить несколько команд в одном задании cron, разделив их точкой с запятой (;
).
* * * * * /path/to/command-1 /path/to/command-2
Если выполняемые команды зависят друг от друга, мы можем использовать двойной амперсанд (&&)
между ними. В результате вторая команда не будет выполняться, если первая не выполняется.
* * * * * /path/to/command-1 /path/to/command-2
Переменные среды
Переменные среды в файлах crontab имеют форму VARIABLE_NAME = VALUE
(пробелы вокруг знака равенства необязательны). Cron не создает никаких файлов запуска из домашнего каталога пользователя (когда он работает на уровне пользователя cron). Это означает, что мы должны вручную установить любые пользовательские настройки, требуемые нашими задачами.
Cron автоматически устанавливает некоторые переменные среды при запуске. HOME
и LOGNAME
устанавливаются из информации владельца crontab /etc/passwd
в. Однако мы можем переопределить эти значения в нашем файле crontab, если в этом есть необходимость.
Есть также еще несколько переменных, например SHELL
, указывающих оболочку, которая выполняет команды. Это /bin/sh
по умолчанию. Мы также можем установить PATH
, в котором искать программы.
/usr/bin/usr/local/bin
Важно: мы должны заключать значение в кавычки, когда в значении есть пробел. Обратите внимание, что значения являются обычными строками. Они не будут интерпретироваться или анализироваться каким-либо образом.
Разные часовые пояса
Cron использует настройку часового пояса системы при оценке записей crontab. Это может вызвать проблемы для многопользовательских систем с пользователями, базирующимися в разных часовых поясах. Чтобы обойти эту проблему, мы можем добавить переменную среды с именем CRON_TZ
в наш файл crontab. В результате все записи crontab будут проанализированы на основе указанного часового пояса.
Как Cron интерпретирует файлы Crontab
После запуска Cron он выполняет поиск в области катушки, чтобы найти и загрузить файлы crontab в память. Он дополнительно проверяет /etc/crontab
/etc/cron.d
каталоги и или для системных crontabs.
После загрузки crontabs в память Cron проверяет загруженные crontabs поминутно, выполняя события, которые должны быть выполнены.
Кроме того, Cron регулярно (каждую минуту) проверяет, изменилось ли modtime
время изменения каталога spool. Если это так, он проверяет modetime
все загруженные crontabs и перезагружает те, которые изменились. Вот почему нам не нужно перезапускать при установке нового задания cron.
Быстрое устранение неполадок
Абсолютный путь к командам
Это хорошая привычка использовать абсолютные пути ко всем исполняемым файлам, которые мы используем в файле crontab.
* * * * * /usr/local/bin/php /absolute/path/to/the/command
Убедитесь, что cron запущен
Если наши задачи вообще не выполняются, сначала нам нужно убедиться, что Cron запущен:
aux crond
Вывод должен быть похож на этот:
root ? Ss :49 crond
Проверка /etc/cron.allow
и /etc/cron.deny
файлы
Когда задания cron не выполняются, нам нужно проверить /etc/cron.allow
, существует ли. Если это так, нам нужно убедиться, что мы перечислили наше имя пользователя в этом файле. И если /etc/cron.deny
существует, нам нужно убедиться, что наше имя пользователя не указано в этом файле.
Если мы редактируем файл crontab пользователя, в то время как пользователь не существует в /etc/cron.allow
файле, включая пользователя в /etc/cron.allow
не будет запускать cron, пока мы не отредактируем файл crontab.
Разрешение на выполнение
Мы должны убедиться, что владелец crontab имеет разрешения на выполнение для всех команд и сценариев в файле crontab. В противном случае cron не будет работать. Вы можете добавить разрешения на выполнение в любую папку или файл с помощью:
+x /some/file.php
Новый символ строки
Каждая запись в crontab должна заканчиваться новой строкой. Это означает, что после последней записи crontab должна быть пустая строка, иначе последнее задание cron никогда не будет выполнено.
How Cron Works
In the case of cron, these events are certain moments in time. Cron runs in the background and checks its configuration file once every minute to see if an event is scheduled to run that minute.
If an event is scheduled, cron executes whatever predetermined command has been given to it and then goes back into the background for another minute. If no event was scheduled, it waits 60 seconds and checks again.
Because of this minute-by-minute scheduling, it is extremely flexible and configurable. Upon installing your distribution, cron is already configured to run a variety of tasks.
Перекрытия задач
Бывают случаи, когда запланированные задачи занимают гораздо больше времени, чем ожидалось. Это приведет к перекрытиям, то есть некоторые задачи могут выполняться одновременно. В некоторых случаях это может не вызвать проблемы, но когда они изменяют одни и те же данные в базе данных, у нас возникнет проблема. Мы можем преодолеть это, увеличив частоту выполнения задач. Тем не менее, нет никакой гарантии, что эти перекрытия не повторятся.
У нас есть несколько вариантов предотвращения перекрытия заданий cron.
Использование Flock
Flock — хороший инструмент для управления файлами блокировки из сценариев оболочки или командной строки. Эти файлы блокировки полезны для того, чтобы узнать, запущен ли скрипт.
При использовании совместно с Cron соответствующие задания cron не запускаются, если файл блокировки существует. Вы можете установить Flock, используя apt-get
или yum,
в зависимости от дистрибутива Linux.
flock
yum flock
Рассмотрим следующую запись crontab:
* * * * * /usr/bin/flock --timeout /path/to/cron.lock /usr/bin/php /path/to/scripts.php
В предыдущем примере flock
ищет /path/to/cron.lock
. Если блокировка будет получена за одну секунду, она запустит скрипт. В противном случае он потерпит неудачу с кодом выхода 1.
Использование механизма блокировки в скриптах
Если задание cron выполняет сценарий, мы можем реализовать механизм блокировки в сценарии. Рассмотрим следующий PHP-скрипт:
?php
sys_get_temp_dir md5__FILE__
file_exists ? trimfile_get_contents null
is_null posix_getsid
// Do something here
// And create/update the lock
file_put_contents, getmypid
exit'Another instance of the script is already running.'
В предыдущем коде мы сохраняем pid
текущий PHP-процесс в файле, который находится в системном temp
каталоге. Каждый PHP-скрипт имеет свой собственный файл блокировки, который является MD5-хэшем имени файла скрипта.
Сначала мы проверяем, существует ли файл блокировки, а затем получаем его содержимое, которое является идентификатором процесса последнего запущенного экземпляра скрипта. Затем мы передаем pid
PHP-функцию posix_getsid , которая возвращает идентификатор сеанса процесса. Если posix_getsid
возвращается false
, это означает, что процесс больше не работает, и мы можем безопасно запустить новый экземпляр.
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):
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.
@hourly ID=greatest_ever_job echo This job is very useful.
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 is a full replacement for dcron which processes jobs asynchronously.
It is provided by . The configuration file is /etc/anacrontab
. Information on the format can be found in the . Running anacron -T
will test /etc/anacrontab
for validity.
Like anacron, 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.
cd /var/spool/cron && ( for ctab in *; do fcrontab ${ctab} -u ${ctab} done )
See also the forum thread.
Prerequisites
To complete this guide, you’ll need access to a computer running Ubuntu 18.04. This could be your local machine, a virtual machine, or a virtual private server.
Using User Specific Crontabs
To see your current crontab, type:
crontab -l
You will probably not have one unless you’ve specifically created it by hand. If you do have a crontab, it is best to backup the current copy before editing so that any changes you make can be reverted.
To store your backup in a file called «cron.bak» in your home directory, run:
crontab -l > ~/cron.back
To edit your crontab, type:
crontab -e
no crontab for demouser - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/nano <---- easiest 2. /usr/bin/vim.basic 3. /usr/bin/vim.tiny
You might be given a selection prompt similar to the one above your first time using this command. Select the editor you prefer to continue.
You will be dropped into a commented file that you can edit to create your own rules.
*/15 * * * 3 echo "$(date)" >> /home/demouser/file
We can then save the file and now, when we run «crontab -l», we should see the rule we just created:
crontab -l
. . . . . . */15 * * * 3 echo "$(date)" >> /home/demouser/file
For instance, if you would like to add something to the «root» crontab, you could issue:
sudo crontab -u root -e
Using Anacron with Cron
One of cron’s biggest weaknesses is that it assumes that your server or computer is always on. If your machine is off and you have a task scheduled during that time, the task will never run.
This is a serious problem with systems that cannot be guaranteed to be on at any given time. Due to this scenario, a tool called «anacron» was developed. Anacron stands for anachronistic, and it is used compensate for this problem with cron.
Anacron uses parameters that are not as detailed as cron’s options. The smallest increment that anacron understands is days. This means that anacron should be used to complement cron, not to replace it.
Anacron’s advantage is that it uses time-stamped files to find out when the last time its commands were executed. This means, if a task is scheduled to be run daily and the computer was turned off during that time, when anacron is run, it can see that the task was last run more than 24 hours ago and execute the task correctly.
The anacron utility has a scheduling table just like cron does. It is appropriately named «anacrontab» and is located in the «/etc» directory as well. Let’s see how it is formatted:
less /etc/anacrontab
# /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # These replace cron's entries 1 5 cron.daily nice run-parts --report /etc/cron.daily 7 10 cron.weekly nice run-parts --report /etc/cron.weekly @monthly 15 cron.monthly nice run-parts --report /etc/cron.monthly
The first column specifies how often the command should be run. It is given as an interval in days. A value of «1» will run every day, while a value of «3» will run every three days.
The second column is the delay to use before executing the commands. Anacron is not a daemon. It is run explicitly at one time. This field allows you to stagger execution so that not every task is running at the same time.
For example, the first line runs every day, five minutes after anacron is called:
1 5 cron.daily nice run-parts --report /etc/cron.daily
7 10 cron.weekly nice run-parts --report /etc/cron.weekly
The third column contains the name that the job will be known as in the anacron’s messages and log files. The fourth field is the actual command that is run.
You can see that anacron is set to run some of the same scripts that are run by cron. Distributions handle this clash differently, by creating a preference for either cron or anacron and making the other program not execute the rule.
For instance, on Ubuntu, the «/etc/crontab» tests if anacron is available on the system, and only executes the scripts in the cron.* directories with cron if anacron is not found.
Other distributions have cron update the anacron’s time-stamps every time it runs the contents of these directories, so that anacron does not execute when it is called.
Перенаправление вывода
Мы можем перенаправить вывод нашего задания cron в файл, если команда (или скрипт) имеет какой-либо вывод:
* * * * * /path/to/php /path/to/the/command /var/log/cron.log
Мы можем перенаправить стандартный вывод на dev null, чтобы не получить электронное письмо, но все же отправить стандартное сообщение об ошибке:
* * * * * /path/to/php /path/to/the/command /dev/null
Чтобы запретить Cron отправлять нам какие-либо электронные письма, мы меняем соответствующую запись crontab, как показано ниже:
* * * * * /path/to/php /path/to/the/command /dev/null
Это означает “отправить как стандартный вывод, так и вывод ошибки в забвение”.
Отправьте вывод по электронной почте
Выходные данные отправляются по почте владельцу crontab или электронной почте (адресам), указанным в переменной MAILTO
среды (если стандартный вывод или стандартная ошибка не перенаправляются, как указано выше).
Если MAILTO
установлено значение empty, в результате выполнения задания cron электронное письмо отправлено не будет.
Мы можем установить несколько писем, разделив их запятыми:
admin@example.com,dev@example.com
* * * * * /path/to/command
Conclusion
Both cron and anacron are useful tools for when you need to automate processes. Understanding how to leverage their strengths and work around their weaknesses will allow you to utilize them easily and effectively.
Although the configuration syntax may be confusing at first, these tools will save you time in the long run and usually do not have to be adjusted often once you have a good working schedule.