- Introduction
- Starting to Use Cron
- Crontab Lines
- Crontab Options
- Allowing/Denying User-Level Cron
- Further Considerations
- Common Problems
- Two Other Types of Crontab
- GUI Applications
- Crontab Example
- How Anacron is Set Up
- Alternatives to Cron
- What cron does
- The de facto cron
- Which cron is right for the job?
- dcron (Dillon’s Cron)
- Is cron running?
- Is cron working?
- Is the command working?
- Can cron run the job?
- Are there any s?
- Why are cron mails not sent out?
- What cron does
- The de facto cron
- Which cron is right for the job?
- dcron (Dillon’s Cron)
- Is cron running?
- Is cron working?
- Is the command working?
- Can cron run the job?
- Are there any s?
- Why are cron mails not sent out?
- Основные понятия cron
- Что делает cron?
- Cron на практике
- Какой cron наиболее подходит?
- dcron (Dillon’s Cron)
- Системный файл crontab
- Предоставление доступа к cron проверенным пользователям
- Планирование заданий cron
- Работает ли команда из задачи cron?
- Может ли cron запустить задание?
- Появляются ли какие-нибудь файлы
- Почему письма cron не отправляются?
Introduction
Cron is a system daemon used to execute desired tasks (in the background) at designated times.
A crontab file is a simple text file containing a list of commands meant to be run at specified times. It is edited using the crontab command. The commands in the crontab file (and their run times) are checked by the cron daemon, which executes them in the system background.
To display the on-line help for crontab enter:
man crontab
or further information is available from the OpenGroup specifications.
On Gnome-based Ubuntu systems Gnome Scheduled tasks tool (from the gnome-schedule package) in Applications —> System Tools provides a graphical interface with prompting for using Cron. The project website is at http://gnome-schedule.sourceforge.net/; the software is installable from the Software Center or by typing
sudo apt-get install gnome-schedule
in a terminal.
Starting to Use Cron
crontab -e
Edit the crontab using the format described in the next sections. Save your changes. (Exiting without saving will leave your crontab unchanged.) To display the on-line help describing the format of the crontab file enter:
man 5 crontab
sudo crontab -e
Crontab Lines
01 04 1 1 1 /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on January 1st plus every Monday in January.
An asterisk (*) can be used so that every instance (every hour, every weekday, every month, etc.) of a time period is used.
01 04 * * * /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on every day of every month.
Comma-separated values can be used to run more than one instance of a particular command within a time period. Dash-separated values can be used to run a command continuously.
01,31 04,05 1-15 1,6 * /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 01 and 31 past the hours of 4:00am and 5:00am on the 1st through the 15th of every January and June.
The «/usr/bin/somedirectory/somecommand» text in the above examples indicates the task which will be run at the specified times. It is recommended that you use the full path to the desired commands as shown in the above examples. Enter which somecommand in the terminal to find the full path to somecommand. The crontab will begin running as soon as it is properly edited and saved.
*/10 * * * * /usr/bin/somedirectory/somecommand
which is also equivalent to the more cumbersome
0,10,20,30,40,50 * * * * /usr/bin/somedirectory/somecommand
Cron also offers some special strings, which can be used in place of the five time-and-date fields:
@reboot /path/to/execuable1
The above example will execute /path/to/executable1 when the system starts.
Crontab Options
- The -l option causes the current crontab to be displayed on standard output.
- The -r option causes the current crontab to be removed.
- The -e option is used to edit the current crontab using the editor specified by the EDITOR environment variable.
After you exit from the editor, the modified crontab is checked for errors and, if there are no errors, it is installed automatically. The file is stored in /var/spool/cron/crontabs but should only be edited using the crontab command.
Allowing/Denying User-Level Cron
joeuser:*:15169::::::
Further Considerations
sudo crontab -e
PATH=/usr/sbin:/usr/bin:/sbin:/bin
crontab -e uses the EDITOR environment variable. To change the editor to your own choice, just set that variable. You may want to set EDITOR in your .bashrc because many commands use this variable. For example, in order to set the editor to be nano (a very easy editor to use) add this line to .bashrc:
export EDITOR=nano
It is sensible to test that your cron jobs work as intended. One method for doing this is to set up the job to run a couple of minutes in the future and then check the results before finalising the timing. You may also find it useful to put the commands into script files that log their success or failure, for example:
echo "Nightly Backup Successful: $(date)" >> /tmp/mybackup.log
Common Problems
Cron jobs may not run with the environment, in particular the PATH, that you expect. Try using full paths to files and programs if they’re not being located as you expect.
The «%» character is used as newline delimiter in cron commands. If you need to pass that character into a script, you need to escape it as «\%».
If you’re having trouble running a GUI application using cron, see the GUI Applications section below.
Two Other Types of Crontab
minute(s) hour(s) day(s)_of_month month(s) day(s)_of_week user command
00 01 * * * rusty /home/rusty/rusty-list-files.sh
Example: Instead of adding a line to /etc/crontab, which Rusty knows is not a good idea, he might well add a file to the directory /etc/cron.d with the name rusty, containing his cron line above. This would not be affected by updates but is a well known location.
GUI Applications
It is possible to run gui applications via cronjobs. This can be done by telling cron which display to use.
00 06 * * * env DISPLAY=:0 gui_appname
The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program «gui_appname».
And if you have multiple monitors, don’t forget to specify on which one the program is to be run. For example, to run it on the first screen (default screen) use :
00 06 * * * env DISPLAY=:0.0 gui_appname
The env DISPLAY=:0.0 portion will tell cron to use the first screen of the current display for the program «gui_appname».
Note: In Karmic(9.10), you have to enable X ACL for localhost to connect to for GUI applications to work.
~$ xhost +local: non-network local connections being added to access control list ~$ xhost access control enabled, only authorized clients can connect LOCAL: ...
Crontab Example
45 04 * * * /usr/bin/updatedb
Save your changes and exit the editor.
Crontab will let you know if you made any mistakes. The crontab will be installed and begin running if there are no errors. That’s it. You now have a cronjob setup to run updatedb, which updates the slocate database, every morning at 4:45.
Note: The double-ampersand (&&) can also be used in the «command» section to run multiple commands consecutively, but only if the previous command exits successfully. A string of commands joined by the double-ampersand will only get to the last command if all the previous commands are run successfully. If exit error-checking is not required, string commands together, separated with a semi-colon (;).
45 04 * * * /usr/sbin/chkrootkit && /usr/bin/updatedb
How Anacron is Set Up
There is a Upstart task, located in /etc/init/anacron.conf, which runs all the jobs in /etc/anacrontab. It is set to run on startup.
There is a cron.d file (/etc/cron.d/anacron) which causes the Upstart task to be started every day at 7:30 AM.
There is a file /etc/apm/event.d/anacron, which causes the Upstart task to be started when a laptop is plugged in to A/C power, or woken up.
In the system crontab (/etc/crontab), if anacron is not execuatable, run‑parts is used to run the files in cron.daily, cron.weekly, and cron.monthly at 6:25 AM, 6:47 AM and 6:52 AM, respectively.
In /etc/anacrontab, run‑parts is used to run cron.daily 5 minutes after anacron is started, and cron.weekly after 10 minutes (once a week), and cron.monthly after 15 (once a month).
Within the cron.daily, weekly, and monthly directories ( /etc/cron.daily, etc.) there is a 0anacron file that sets the timestamps for anacron, so it will know they have been run, even if it didn’t run them.
So it appears anacron is run on every startup, wake up, plug-in, and at 7:30 AM every day. Looking at the respective Changelogs and package databases, it looks like this setup is directly from Debian, and hasn’t been changed since at least 2009.
Alternatives to Cron
Some hosting companies don’t allow access to cron, but there are websites offering alternative ways of scheduling jobs (free or paid-for). Here are some examples:
This article describes how to setup and use cron daemons in Gentoo Linux.
What cron does
Note
Notice that is both the name of a list of cron-jobs as well as the name of the command to edit that list.
The de facto cron
There are a few cron implementations to choose from in Portage. All of them offer a similar interface, namely the use of or a similar command. There is also a related utility called Anacron which is meant to work with cron on systems that are not continuously running.
Before getting started working with cron, a proper cron implementation has to be selected.
Which cron is right for the job?
Note
Emerge virtual/cron to install Gentoo’s default cron implementation.
sys-process/cronie is a fork of now outdated vixie-cron done by Fedora, which is still maintained. Because of it being a fork it has the same feature set the original vixie-cron provides. Additionally cronie comes with an anacron implementation which is enabled by default, through the anacron
USE flag. Be aware of the configuration differences as noted in bug #551352 when migrating from another cron system. Expected jobs may not run at all.
dcron (Dillon’s Cron)
Features of sys-process/dcron:
- Fast, simple and free of unnecessary features;
- Access to is limited to the cron group, i.e. it doesn’t rely on any external faculties.
sys-process/fcron aims at replacing vixie-cron and anacron. It is designed to work on systems that are not continuously running and it is packed with extra features. It has job startup constraints, job serialization controls, the ability to assign nice values to jobs and the ability to schedule jobs to run at system startup.
Features of sys-process/fcron:
- Designed to work on systems that are not continuously running, i.e. it can run a job after restarting if it was missed;
- Setting of environment variables and many other options in crontabs;
- Enhanced crontab syntax with support for many new features;
- Each user can have a personal crontab, access is controlled by and
Features of sys-process/bcron:
- Drop-in replacement for vixie-cron;
- Multiprocess design;
- Native daylight savings time support.
Anacron is not a cron daemon, it is something that usually works in conjunction with one. It executes commands at intervals specified in days and it does not assume that the system is running continuously; it will run jobs that were missed while the system was down. Anacron usually relies on a cron daemon to run it each day.
Select the right cron implementation for the job, and then emerge it:
Make sure the cron daemon of choice has been added to the system’s init process; without this step the cron daemon will not perform its job.
root
/etc/init.d/dcron start
root
rc-update add dcron default
Optionally, if Fcron or dcron have not been installed, installing Anacron as a helper to the cron daemon might be a wise choice.
root
emerge --ask anacron
Again, do not forget to add anacron to the system’s init process.
root
/etc/init.d/anacron start
root
rc-update add anacron default
For anacron, there is usually no init process. Instead, anacron needs to be launched through a different cron implementation.
One method is to launch anacron through a cron definition. By default, it installs an hourly run script, which is consumed by most cron implementations. If that isn’t the case though, then it can still be launched through manual definitions:
/etc/crontab
Launching anacron through a cron definition
# Start anacron every 10 minutes */10 * * * root /usr/sbin/anacron # Alternatively, run the anacron-provided 0anacron script every hour # 59 * * * * root /etc/cron.hourly/0anacron
Please note that jobs scheduled in the system crontab might not show up in the list of cron-jobs displayed by running .
root
sed -i -e "s/^/#/" /etc/crontab
root
gpasswd -a larry cron
Permissions in fcron.deny
all
Permissions in fcron.allow
larry
If cronie has been chosen, then simply edit the file.
Permissions in /etc/cron.allow
larry
Note
Fcron also has a symlink from crontab to fcrontab.
That sounds a little confusing, but with a few examples it is easy to see it is not as complicated as it sounds.
# Run /bin/false every minute year round * * * * * /bin/false # Run /bin/false at 1:35 on the mon,tue,wed and the 4th of every month 35 1 4 * mon-wed /bin/false # Run /bin/true at 22:25 on the 2nd of March 25 22 2 3 * /bin/true # Run /bin/false at 2:00 every Monday, Wednesday and Friday 0 2 * * 1-5/2 /bin/false
Note
Notice how to specify specific days of the week and days of the month before they are combined. If * is used for only one of them, the other takes precedence, while * for both just means every day.
To test what was just covered go through the steps of actually inputting a few cron-jobs. First, create a file called and make it look like the this:
crons.cron
Create a crons.cron file
#Mins Hours Days Months Day of the week 10 3 1 1 * /bin/echo "I don't really like cron" 30 16 * 1,2 * /bin/echo "I like cron a little" * * * 1-12/2 * /bin/echo "I really like cron"
Now add that crontab to the system with the «new command» from the table above.
To verify the scheduled cron-jobs, use the proper list command from the table above.
A list resembling should be displayed; if not maybe the wrong command was issued to input the crontab.
If using anacron keep reading this section. Otherwise, proceed to the next section on Editing crontabs.
5 10 wasting-time /bin/echo "I like anacron"
Anacron exits after all of the jobs in anacrontab have finished. To check to see if these jobs should be performed every day, a cron daemon will be used. The instructions at the end of the next section explain how this should be handled.
root
crontab -d
root
crontab -l
No cron-jobs should be displayed in the output from . If cron jobs are listed, then the remove command failed to remove the crontab; verify the correct remove command for the system’s cron package.
A real crontab
22 2 * * 1 /usr/bin/updatedb
That would make cron run updatedb at 2:22 A.M. on Monday morning every week. Now input the crontab with the proper new command from the table above, and check the list again.
root
crontab crons.cron
root
crontab -l
A real crontab
22 2 * * 1 /usr/bin/updatedb 30 6 * * * /usr/bin/emerge --sync ## (if using anacron, add this line) 30 7 * * * /usr/sbin/anacron -s
Again, check the cron-jobs list as done in the previous examples to make sure the jobs are scheduled. If they are all there, then the system is ready to rock and roll.
Default system crontab
*/15 * * * * test -x /usr/sbin/run-crons && /usr/sbin/run-crons 0 * * * * rm -f /var/spool/cron/lastrun/cron.hourly 0 3 * * * rm -f /var/spool/cron/lastrun/cron.daily 15 4 * * 6 rm -f /var/spool/cron/lastrun/cron.weekly 30 5 1 * * rm -f /var/spool/cron/lastrun/cron.monthly
To avoid going into much detail, assume these commands will effectively run hourly, daily, weekly and monthly scripts. This method of scheduling cron-jobs has some important advantages:
- They will run even if the computer was off when they were scheduled to run;
- It is easy for package maintainers to place scripts in those well defined places;
- The administrators know exactly where the cron-jobs and crontab are stored, making it easy to backup and restore these parts of their systems.
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # format: period delay job-identifier command 1 5 cron.daily run-parts /etc/cron.daily 7 10 cron.weekly run-parts /etc/cron.weekly 30 15 cron.monthly run-parts /etc/cron.monthly
The main difference between this and other common crontabs is that with anacron there is no fixed date/hour for the job scheduling, but only the period between every run. When anacron is started, it will check the contents of a set of files in and calculate if the corresponding entry in the configuration file has expired since the last run. If it has, then the command is invoked again.
# for cronie # Global variables SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # check scripts in cron.hourly, cron.daily, cron.weekly, and cron.monthly 59 * * * * root rm -f /var/spool/cron/lastrun/cron.hourly #9 3 * * * root rm -f /var/spool/cron/lastrun/cron.daily #19 4 * * 6 root rm -f /var/spool/cron/lastrun/cron.weekly #29 5 1 * * root rm -f /var/spool/cron/lastrun/cron.monthly #*/10 * * * * root test -x /usr/sbin/run-crons && /usr/sbin/run-crons @hourly root test ! -e /var/spool/cron/lastrun/cron.hourly && touch /var/spool/cron/lastrun/cron.hourly && run-parts --report /etc/cron.hourly
Without doing this, the daily, weekly, and monthly parts will be executed — at different times — by both the cron daemon and anacron, leading to possible double job executions.
When having problems getting cron to work properly, this quick checklist might be helpful.
Remember, each cron package is different and the range of features varies greatly. Be sure to consult the man pages for crontab, fcrontab, or anacrontab, depending on which cron daemon has been activated!
Is cron running?
To verify that cron is running, see if it shows up in the process list:
Is cron working?
crontab to see if cron is running
* * * * * /bin/echo "foobar" >> /tmp/file_you_own.log
Then check if is modified periodically.
Is the command working?
Same as before, but perhaps redirect the standard error output as well:
crontab to verify application runs
* * * * * /bin/echo "foobar" >> /tmp/file_you_own 2>&1
Can cron run the job?
Check the cron log, usually or for errors.
Are there any s?
cron usually sends mail when there is a problem; check for mail and look for the creation of a file.
Why are cron mails not sent out?
In order to receive mails from cron, a valid MTA setup must be implemented. This is provided by any package from virtual/mta.
If the cron mails are only to be sent locally, and not through a fully configured mail server, the system can use mbox () mails, by enabling the mbox useflag with the respective package which provides the MTA.
- https://crontab.guru/
This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Eric Brown, Xavier Neys,
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article’s associated history page.
This article describes how to setup and use cron daemons in Gentoo Linux.
What cron does
Note
Notice that is both the name of a list of cron-jobs as well as the name of the command to edit that list.
The de facto cron
There are a few cron implementations to choose from in Portage. All of them offer a similar interface, namely the use of or a similar command. There is also a related utility called Anacron which is meant to work with cron on systems that are not continuously running.
Before getting started working with cron, a proper cron implementation has to be selected.
Which cron is right for the job?
Note
Emerge virtual/cron to install Gentoo’s default cron implementation.
sys-process/cronie is a fork of now outdated vixie-cron done by Fedora, which is still maintained. Because of it being a fork it has the same feature set the original vixie-cron provides. Additionally cronie comes with an anacron implementation which is enabled by default, through the anacron
USE flag. Be aware of the configuration differences as noted in bug #551352 when migrating from another cron system. Expected jobs may not run at all.
dcron (Dillon’s Cron)
Features of sys-process/dcron:
- Fast, simple and free of unnecessary features;
- Access to is limited to the cron group, i.e. it doesn’t rely on any external faculties.
sys-process/fcron aims at replacing vixie-cron and anacron. It is designed to work on systems that are not continuously running and it is packed with extra features. It has job startup constraints, job serialization controls, the ability to assign nice values to jobs and the ability to schedule jobs to run at system startup.
Features of sys-process/fcron:
- Designed to work on systems that are not continuously running, i.e. it can run a job after restarting if it was missed;
- Setting of environment variables and many other options in crontabs;
- Enhanced crontab syntax with support for many new features;
- Each user can have a personal crontab, access is controlled by and
Features of sys-process/bcron:
- Drop-in replacement for vixie-cron;
- Multiprocess design;
- Native daylight savings time support.
Anacron is not a cron daemon, it is something that usually works in conjunction with one. It executes commands at intervals specified in days and it does not assume that the system is running continuously; it will run jobs that were missed while the system was down. Anacron usually relies on a cron daemon to run it each day.
Select the right cron implementation for the job, and then emerge it:
Make sure the cron daemon of choice has been added to the system’s init process; without this step the cron daemon will not perform its job.
root
/etc/init.d/dcron start
root
rc-update add dcron default
Optionally, if Fcron or dcron have not been installed, installing Anacron as a helper to the cron daemon might be a wise choice.
root
emerge --ask anacron
Again, do not forget to add anacron to the system’s init process.
root
/etc/init.d/anacron start
root
rc-update add anacron default
For anacron, there is usually no init process. Instead, anacron needs to be launched through a different cron implementation.
One method is to launch anacron through a cron definition. By default, it installs an hourly run script, which is consumed by most cron implementations. If that isn’t the case though, then it can still be launched through manual definitions:
/etc/crontab
Launching anacron through a cron definition
# Start anacron every 10 minutes */10 * * * root /usr/sbin/anacron # Alternatively, run the anacron-provided 0anacron script every hour # 59 * * * * root /etc/cron.hourly/0anacron
Please note that jobs scheduled in the system crontab might not show up in the list of cron-jobs displayed by running .
root
sed -i -e "s/^/#/" /etc/crontab
root
gpasswd -a larry cron
Permissions in fcron.deny
all
Permissions in fcron.allow
larry
If cronie has been chosen, then simply edit the file.
Permissions in /etc/cron.allow
larry
Note
Fcron also has a symlink from crontab to fcrontab.
That sounds a little confusing, but with a few examples it is easy to see it is not as complicated as it sounds.
# Run /bin/false every minute year round * * * * * /bin/false # Run /bin/false at 1:35 on the mon,tue,wed and the 4th of every month 35 1 4 * mon-wed /bin/false # Run /bin/true at 22:25 on the 2nd of March 25 22 2 3 * /bin/true # Run /bin/false at 2:00 every Monday, Wednesday and Friday 0 2 * * 1-5/2 /bin/false
Note
Notice how to specify specific days of the week and days of the month before they are combined. If * is used for only one of them, the other takes precedence, while * for both just means every day.
To test what was just covered go through the steps of actually inputting a few cron-jobs. First, create a file called and make it look like the this:
crons.cron
Create a crons.cron file
#Mins Hours Days Months Day of the week 10 3 1 1 * /bin/echo "I don't really like cron" 30 16 * 1,2 * /bin/echo "I like cron a little" * * * 1-12/2 * /bin/echo "I really like cron"
Now add that crontab to the system with the «new command» from the table above.
To verify the scheduled cron-jobs, use the proper list command from the table above.
A list resembling should be displayed; if not maybe the wrong command was issued to input the crontab.
If using anacron keep reading this section. Otherwise, proceed to the next section on Editing crontabs.
5 10 wasting-time /bin/echo "I like anacron"
Anacron exits after all of the jobs in anacrontab have finished. To check to see if these jobs should be performed every day, a cron daemon will be used. The instructions at the end of the next section explain how this should be handled.
root
crontab -d
root
crontab -l
No cron-jobs should be displayed in the output from . If cron jobs are listed, then the remove command failed to remove the crontab; verify the correct remove command for the system’s cron package.
A real crontab
22 2 * * 1 /usr/bin/updatedb
That would make cron run updatedb at 2:22 A.M. on Monday morning every week. Now input the crontab with the proper new command from the table above, and check the list again.
root
crontab crons.cron
root
crontab -l
A real crontab
22 2 * * 1 /usr/bin/updatedb 30 6 * * * /usr/bin/emerge --sync ## (if using anacron, add this line) 30 7 * * * /usr/sbin/anacron -s
Again, check the cron-jobs list as done in the previous examples to make sure the jobs are scheduled. If they are all there, then the system is ready to rock and roll.
Default system crontab
*/15 * * * * test -x /usr/sbin/run-crons && /usr/sbin/run-crons 0 * * * * rm -f /var/spool/cron/lastrun/cron.hourly 0 3 * * * rm -f /var/spool/cron/lastrun/cron.daily 15 4 * * 6 rm -f /var/spool/cron/lastrun/cron.weekly 30 5 1 * * rm -f /var/spool/cron/lastrun/cron.monthly
To avoid going into much detail, assume these commands will effectively run hourly, daily, weekly and monthly scripts. This method of scheduling cron-jobs has some important advantages:
- They will run even if the computer was off when they were scheduled to run;
- It is easy for package maintainers to place scripts in those well defined places;
- The administrators know exactly where the cron-jobs and crontab are stored, making it easy to backup and restore these parts of their systems.
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # format: period delay job-identifier command 1 5 cron.daily run-parts /etc/cron.daily 7 10 cron.weekly run-parts /etc/cron.weekly 30 15 cron.monthly run-parts /etc/cron.monthly
The main difference between this and other common crontabs is that with anacron there is no fixed date/hour for the job scheduling, but only the period between every run. When anacron is started, it will check the contents of a set of files in and calculate if the corresponding entry in the configuration file has expired since the last run. If it has, then the command is invoked again.
# for cronie # Global variables SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # check scripts in cron.hourly, cron.daily, cron.weekly, and cron.monthly 59 * * * * root rm -f /var/spool/cron/lastrun/cron.hourly #9 3 * * * root rm -f /var/spool/cron/lastrun/cron.daily #19 4 * * 6 root rm -f /var/spool/cron/lastrun/cron.weekly #29 5 1 * * root rm -f /var/spool/cron/lastrun/cron.monthly #*/10 * * * * root test -x /usr/sbin/run-crons && /usr/sbin/run-crons @hourly root test ! -e /var/spool/cron/lastrun/cron.hourly && touch /var/spool/cron/lastrun/cron.hourly && run-parts --report /etc/cron.hourly
Without doing this, the daily, weekly, and monthly parts will be executed — at different times — by both the cron daemon and anacron, leading to possible double job executions.
When having problems getting cron to work properly, this quick checklist might be helpful.
Remember, each cron package is different and the range of features varies greatly. Be sure to consult the man pages for crontab, fcrontab, or anacrontab, depending on which cron daemon has been activated!
Is cron running?
To verify that cron is running, see if it shows up in the process list:
Is cron working?
crontab to see if cron is running
* * * * * /bin/echo "foobar" >> /tmp/file_you_own.log
Then check if is modified periodically.
Is the command working?
Same as before, but perhaps redirect the standard error output as well:
crontab to verify application runs
* * * * * /bin/echo "foobar" >> /tmp/file_you_own 2>&1
Can cron run the job?
Check the cron log, usually or for errors.
Are there any s?
cron usually sends mail when there is a problem; check for mail and look for the creation of a file.
Why are cron mails not sent out?
In order to receive mails from cron, a valid MTA setup must be implemented. This is provided by any package from virtual/mta.
If the cron mails are only to be sent locally, and not through a fully configured mail server, the system can use mbox () mails, by enabling the mbox useflag with the respective package which provides the MTA.
- https://crontab.guru/
This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Eric Brown, Xavier Neys,
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article’s associated history page.
Эта статья описывает установку и использование демонов cron в Gentoo Linux.
Основные понятия cron
Что делает cron?
Cron — это программа-демон, запускающая запланированные задания, основываясь на результате работы команды . Она выполняет эти задания просыпаясь каждую минуту и проверяя, есть ли какие-нибудь задания cron (cron-jobs) для запуска в каком-либо из файлов заданий crontab пользователя.
Заметка
Заметьте, что — это как имя списка заданий cron, так и имя команды для редактирования этого списка.
Заметка
При использовании системы инициализации systemd доступны (постояннные) таймеры в качестве замены (ana)cron.
Cron на практике
Существует несколько реализаций программы cron, доступных через Portage. Все они предлагают сходный интерфейс, а именно, использование команды или ей подобных. Также есть родственная утилита, называемая Anacron, которая предназначена для работы с cron-ом на системах, которые не работают непрерывно.
Все доступные пакеты cron зависят от sys-process/cronbase. Технически, этот пакет не является зависимостью какого-либо из пакетов cron, но он предлагает сходную с cron-ом функциональность, которую смогут оценить многие пользователи.
Перед тем, как начать работу с cron, следует выбрать наиболее подходящую реализацию cron.
Какой cron наиболее подходит?
Заметка
Установите virtual/cron для получения стандартной реализации cron на Gentoo.
Cronie (sys-process/cronie) — это ответвление от устаревшего vixie-cron, сделанное дистрибутивом Fedora и всё ещё поддерживаемое. У данной программы имеется тот же набор возможностей, что и у оригинального vixie-cron. Дополнительно, cronie имеет включённую по умолчанию (через USE-флаг anacron
) реализацию anacron. Убедитесь, что в случае миграции с другой системы cron изучили изменения, описанные в bug #551352. Некоторые задачи могут перестать выполняться.
dcron (Dillon’s Cron)
sys-process/dcron стремится быть простой, элегантной и безопасной реализацией программы cron. Он не разрешает установку переменных среды в файлах crontabs и все задания cron запускаются из . Как и vixie-cron, каждый пользователь имеет свой собственный файл заданий crontab. С 4 версии он поддерживает anacron-подобные возможности.
- Быстрый, простой и свободный от излишних функций;
- Доступ к файлу ограничен группой cron, т.е. он не полагается на внешние средства.
sys-process/fcron ориентирован на то, чтобы заменить собой vixie-cron и anacron. Он разработан для работы на системах, которые не работают непрерывно и включает в себя дополнительные особенности. Он имеет ограничения на запуск заданий, управление сериализацией работ, возможность назначить работам приятные в обращении значения и возможность запланировать запуск работ при загрузке системы.
- Разработан для работы на системах, которые не работают непрерывно, т.е. он может запустить задание после перезапуска, если оно было пропущено;
- Установка переменных среды и множества других параметров в файлах заданий crontab;
- Улучшенный синтаксис crontab с поддержкой множества новых функций;
- У каждого пользователя может быть личный файл заданий crontab; доступ контролируется файлами и
sys-process/bcron — это новая система cron, разработанная с учетом безопасности её работы. Чтобы добиться этого, система поделена на несколько отдельных программ, каждая из которых отвечает за отдельное задание, со строго контролируемым сообщением между ними. Пользовательский интерфейс представляет собой несущественное изменение интерфейсов для подобных систем (таких как vixie-cron), но внутренние части программы сильно отличаются.
- Легкая замена vixie-cron;
- Ориентированность на множество процессов;
- Нативная поддержка перехода на летнее время.
Anacron — это не демон cron, это то, что работает в объединении с ним. Он выполняет команды по интервалам в указанные дни и не предполагает непрерывную работу системы; он запускает работы, которые были пропущены, пока система была отключена. Anacron обычно полагается на демон cron, чтобы запускаться каждый день.
Выберите реализацию cron, которая наиболее подходит, и установите ее командой emerge:
Убедитесь, что демон cron добавлен в процесс инициализации системы; без этого шага cron демон не будет выполнять свою работу.
root
/etc/init.d/dcron start
root
rc-update add dcron default
Опционально, если fcron или dcron не был установлен, то установка Anacron в качестве помощника cron демона может быть мудрым решением.
root
emerge --ask anacron
Опять же, не забудьте добавить Anacron для запуска во время инициализации системы.
root
/etc/init.d/anacron start
root
rc-update add anacron default
У anacron обычно нет процесса инициализации. Вместо этого anacron нужно запускать с помощью другой реализации cron.
Один из методов запуска anacron — через определение cron. По умолчанию, anacron устанавливает сценарий почасового запуска, который используется большинством реализаций cron. Если этого не происходит, anacron всё же можно запустить с помощью ручных определений.
/etc/crontab
Запуск anacron с помощью определения cron
# Запускать anacron каждые 10 минут */10 * * * root /usr/sbin/anacron # В качестве альтернативы, каждый час выполнять сценарий 0anacron, предоставленный anacron # 59 * * * * root /etc/cron.hourly/0anacron
Системный файл crontab
Пожалуйста, возьмите на заметку, что задания, запланированные в системном crontab могут не появиться в списке заданий cron, отображаемом при использовании .
Конечно, пользователь может не использовать какой-либо системный файл crontab вовсе. Если был выбран dcron или fcron, не запускайте . Если был выбран cronie или bcron закомментируйте все строки в .
Быстрый и простой способ закомментировать все строки в файле с помощью команды sed. Выполните следующую команду, чтобы закомментировать все строки в
root
sed -i -e "s/^/#/" /etc/crontab
Предоставление доступа к cron проверенным пользователям
Не имеет значения какой из пакетов cron был выбран, если нужно разрешить пользователю использование crontab, то он должен быть в группе cron. В качестве примера, для добавления пользователя larry в группу cron нужно запустить:
root
gpasswd -a larry cron
Заметка
При добавлении пользователя в группу cron, убедитесь, что пользователь вышел и снова зашел в систему, чтобы изменения в группе возымели эффект.
При использовании fcron, отредактируйте и файлы. Наиболее безопасный способ запуска системы — это сперва запретить всех пользователей в файле , а затем явно разрешить пользователей в .
Важно
Если файлы и не существуют, тогда всем пользователям в группе cron будет разрешено использовать crontab. fcron поставляется с файлом , который по умолчанию разрешает всем пользователям, находящимся в группе cron, доступ к fcrontab.
Разрешения в fcron.deny
all
Если пользователю larry (опять для примера) необходимо управлять его собственными заданиями cron, тогда добавьте его в , как показано ниже:
Разрешения в fcron.allow
larry
Если был выбран cronie, возможно, нужно просто отредактировать файл.
Важно
Важно заметить что если существует только файл , то только пользователи, принадлежащие группе cron, перечисленные в нем, будут иметь доступ. Иначе, если существует только пустой файл , то доступ всем пользователям, принадлежащим группе cron будет разрешен! Не оставляйте файл пустым, если нет файла.
Например, чтобы разрешить доступ пользователю larry, добавьте его в как показано ниже:
Разрешения в /etc/cron.allow
larry
Планирование заданий cron
Процесс редактирования файлов crontab различен для каждого пакета, но все они поддерживают базовый набор команд: добавление и замещение файлов crontab, редактирование и удаление файлов crontab, список cron заданий из crontab файлов. Следующий список показывает, как выполнять различные команды для каждого пакета.
Заметка
Если не указано ни одного аргумента при использовании команды удаления, она удаляет файл crontab текущего пользователя.
Заметка
Fcron также имеет символьную ссылку с crontab на fcrontab.
Перед использованием какой-либо из этих команд, нужно сперва понять работу самого crontab. В каждой строке файла crontab нужно указать пять полей со временем в следующем порядке: минуты (0-59), часы (0-23), дни месяца (1-31), месяцы (1-12), и дни недели (0-7, Понедельник — 1, Воскресенье — 0 и 7). Дни недели и месяцы могут быть указаны трехбуквенными сокращениями, например mon,tue,jan,feb, и т.д. Каждое поле также может указывать диапазон значений (напр. 1-5 или mon-fri), список значений, разделенный запятыми (напр. 1,2,3 или mon,tue,wed) или диапазон значений с шагом (напр. 1-6/2 как 1,3,5).
Звучит немного запутанно, но на нескольких примерах нетрудно увидеть, что это не так сложно, как кажется.
# Запускать /bin/false каждую минуту круглый год * * * * * /bin/false # Запускать /bin/false в 1:35 в mon,tue,wed (понедельник, вторник, среду) и 4-й день каждого месяца 35 1 4 * mon-wed /bin/false # Запускать /bin/true в 22:25 на 2-е Марта 25 22 2 3 * /bin/true # Запускать /bin/false в 2:00 каждый Понедельник, Среду и Пятницу 0 2 * * 1-5/2 /bin/false
Заметка
Обратите внимание, как нужно записывать дни недели и дни месяца перед тем, как их сгруппировать. Если использовать * только для одной категории, другие возьмут приоритет, в то время как * для обоих просто означает каждый день.
Чтобы протестировать только что изученное, давайте разберем по шагам фактический ввод нескольких заданий cron. Для начала, создайте файл с названием и приведите его к следующему виду:
crons.cron
Создание файла crons.cron
#Минуты Часы Дни Месяцы Дни недели 10 3 1 1 * /bin/echo "Мне действительно не нравится cron" 30 16 * 1,2 * /bin/echo "Мне нравится cron немного" * * * 1-12/2 * /bin/echo "Мне нравится cron в самом деле"
Теперь добавьте этот crontab в систему с помощью команды Новый crontab из таблицы выше.
Чтобы проверить запланированные задачи cron, мы используем соответственную команду Перечислить cron-jobs из таблицы выше.
Список напоминающий должен быть показан. Если этого не произошло, возможно, использовалась неверная команда для ввода файла crontab.
Этот файл заданий crontab должен выводить «Мне нравится cron в самом деле» каждую минуту каждый час каждого дня каждого второго месяца. Очевидно, что пользователю следует это делать только если ему действительно понравился cron. Этот crontab также выведет «Мне нравится cron немного» в 16:30 каждый день в Январе и Феврале. Он также будет выводить «Мне действительно не нравится cron» в 3:10 1-го Января.
Если используется anacron, то следует продолжить чтение этого раздела. Иначе, перейдите к следующему разделу Редактирование crontabs.
Пользователи Anacron, возможно, захотят отредактировать . Этот файл имеет четыре поля: количество дней перед каждым запуском, задержка в минутах после которой он запускает задания, имя задания, и команда для запуска.
5 10 wasting-time /bin/echo "Мне нравится anacron"
Anacron завершается после того, как сделаны все задания, перечисленные в файле anacrontab. Чтобы проверить, есть ли задания для ежедневного выполнения, нам потребуется использовать cron. Инструкции в конце следующего раздела покажут как это сделать.
Все же, давайте будем реалистами. Наверное нет пользователей, которые хотят, чтобы система сообщала им каждую минуту как сильно они любят cron. Как шаг вперед, давайте удалим этот crontab, используя соответствующую команду Удалить crontab из таблицы выше. Используйте соответствующую команду для получения списка задач cron, чтобы убедиться что команда сработала.
root
crontab -d
root
crontab -l
no cron jobs долно быть показано в качестве результата работы команды . Если был показан список заданий, это значит, что команда удаления не смогла удалить crontab; проверьте, что используется правильная команда Удалить для этого пакета cron.
Теперь, когда мы можем начать с чистого листа, давайте поместим что-нибудь полезное в файл crontab принадлежащий root. Большинство пожелает запускать команду еженедельно, чтобы убедиться, что mlocate работает как надо. Чтобы добавить это в системный crontab, давайте сначала отредактируем файл заново, чтобы он принял следующий вид:
Настоящий crontab
22 2 * * 1 /usr/bin/updatedb
Это заставит cron запускать updatedb в 2:22 A.M. утром в понедельник каждую неделю. Теперь можно ввести этот crontab с помощью команды Новый crontab из таблицы выше, и проверить список снова.
root
crontab crons.cron
root
crontab -l
Теперь, давайте предположим, что нужно добавить команду к ежедневному выполнению, чтобы сохранить дерево Portage всегда в свежем виде. Это можно сделать сперва отредактировав файл и затем используя команду так, как в примере ранее, или используйте соответствующую команду Редактировать crontab из таблицы выше. Это предоставляет способ редактировать crontab пользователя в любом месте, вне зависимости от внешних файлов, наподобие .
Эта команда должна открыть crontab пользователя в редакторе. Например, если команда будет выполняться каждый день в 6:30 A.M., сделайте чтобы crontab выглядел так:
Настоящий crontab
22 2 * * 1 /usr/bin/updatedb 30 6 * * * /usr/bin/emerge --sync ## (если используется anacron, добавьте эту строчку) 30 7 * * * /usr/sbin/anacron -s
И снова, проверьте список заданий cron, так же, как делали в предыдущих примерах, чтобы убедиться что задания запланированы. Если все они перечислены там, то система готова к рок-н-роллу.
Системный crontab по умолчанию
*/15 * * * * test -x /usr/sbin/run-crons && /usr/sbin/run-crons 0 * * * * rm -f /var/spool/cron/lastrun/cron.hourly 0 3 * * * rm -f /var/spool/cron/lastrun/cron.daily 15 4 * * 6 rm -f /var/spool/cron/lastrun/cron.weekly 30 5 1 * * rm -f /var/spool/cron/lastrun/cron.monthly
Чтобы избежать углубления в излишние подробности, предположим, что эти команды будут фактически запускать ваши сценарии каждый час, день, неделю и месяц. Этот метод планирования задач cron имеет несколько важных преимуществ:
- они будут запускаться даже когда компьютер был выключен, в то время, когда им было необходимо выполниться;
- облегчается работа сопроводителей пакета по размещению сценариев в тех хорошо определенных местах;
- администратор точно знаете где хранятся задачи cron и crontab, что делает легким процесс создания резервных копий и восстановления этой части системы.
Заметка
И снова, полезно отметить, что cronie и bcron автоматически считывают содержимое файла , в то время как dcron и fcron — нет. В разделе Системный файл crontab это описано подробнее.
Как было упомянуто ранее, anacron используется на системах, не предназначенных для непрерывной работы (подобно большинству настольных компьютеров). Его файл конфигурации по умолчанию, , обычно выглядит так:
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # format: period delay job-identifier command 1 5 cron.daily run-parts /etc/cron.daily 7 10 cron.weekly run-parts /etc/cron.weekly 30 15 cron.monthly run-parts /etc/cron.monthly
Главным различием между этим файлом crontab и другими является то, что у anacron-а нет фиксированной даты/часа для планирования работы, но только период между каждым запуском. Когда anacron запущен, он проверит содержимое набора файлов в и вычислит, не истекла ли соответствующая запись в файле конфигурации с момента предыдущего запуска. Если это произошло, то команда вызывается снова.
В заключение, важно закомментировать какие-либо совпадающие записи в любом другом cron, установленном на системе, так, как в следующем примере с файлом crontab программы vixie-cron:
# for cronie # Глобальные переменные SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # Проверка сценариев в cron.hourly, cron.daily, cron.weekly и cron.monthly 59 * * * * root rm -f /var/spool/cron/lastrun/cron.hourly #9 3 * * * root rm -f /var/spool/cron/lastrun/cron.daily #19 4 * * 6 root rm -f /var/spool/cron/lastrun/cron.weekly #29 5 1 * * root rm -f /var/spool/cron/lastrun/cron.monthly #*/10 * * * * root test -x /usr/sbin/run-crons && /usr/sbin/run-crons @hourly root test ! -e /var/spool/cron/lastrun/cron.hourly && touch /var/spool/cron/lastrun/cron.hourly && run-parts --report /etc/cron.hourly
Без этого, части daily, weekly и monthly будут выполняться — в разное время — как демоном cron, так и anacron, приводя к возможным повторениям выполнения работ.
Если появляются проблемы во время работы cron, этот краткий список может быть полезным.
Запомните, каждый пакет cron отличается от других, и диапазон возможностей сильно разнится. Проконсультируйтесь с man-страницами для crontab, fcrontab или anacrontab, в зависимости от того, какой cron демон используется.
Чтобы убедиться, что cron работает, посмотрите, если он в списке процессов:
Пример файла crontab для того, чтобы проверить работает ли cron
* * * * * /bin/echo "foobar" >> /tmp/file_you_own.log
Затем проверьте модифицируется ли файл периодически.
Работает ли команда из задачи cron?
То же самое, что и раньше, но также перенаправьте стандартный вывод ошибок:
Пример файла crontab для того, чтобы проверить работает ли cron
* * * * * /bin/echo "foobar" >> /tmp/file_you_own 2>&1
Может ли cron запустить задание?
Проверьте лог-файл cron, обычно или , на ошибки.
Появляются ли какие-нибудь файлы
Cron обычно отправляет сообщение в случае проблемы; проверьте почту и файл.
Почему письма cron не отправляются?
Чтобы получать почту от cron, должен быть правильно установлен и настроен MTA. Такая возможность предоставляется любым пакетом из virtual/mta.
Если почтовые сообщения cron отправляются только локально, а не через полностью настроенный почтовый сервер, система может использовать почту mbox (), включив USE-флаг mbox в соответствующим пакете, который предоставляет MTA.
- https://crontab.guru/
This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Eric Brown, Xavier Neys,
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article’s associated history page.
# cat /etc/cron.deny johny
$ crontab -e You (johny) are not allowed to use this program (crontab) See crontab(1) for more information
# ls -lrt /usr/bin/crontab -rwsr-xr-x 1 root root 57552 Apr 21 2015 /usr/bin/crontab
Change The permission (remove the setuid bit) :
# chmod 700 /usr/bin/crontab # ls -lrt /usr/bin/crontab -rwx------ 1 root root 57552 Apr 21 2015 /usr/bin/crontab
Note: Make sure you have backup file before change its file permission.
After package upgrade, this change will be reversed to default.
Default permission:
# stat /usr/bin/crontab File: ‘/usr/bin/crontab’ Size: 57552 Blocks: 120 IO Block: 4096 regular file Device: fd00h/64768d Inode: 10751442 Links: 1 Access: (4755/-rwsr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2016-08-12 17:03:10.112443944 +0530 Modify: 2015-04-21 19:38:05.000000000 +0530 Change: 2016-03-14 14:03:30.347276747 +0530 Birth: -
$ crontab -e bash: /usr/bin/crontab: Permission denied
# cat /etc/cron.deny oracle
# crontab -e You (oracle) are not allowed to use this program (crontab) See crontab(1) for more information
# ls -lrt /usr/bin/crontab -rwsr-xr-x 1 root root 51784 Jul 22 2016 /usr/bin/crontab
After removing the execute permission :
# chmod 700 /usr/bin/crontab # ls -lrt /usr/bin/crontab -rwx----- 1 root root 51784 Jul 22 2016 /usr/bin/crontab
Note: Make sure you have backup of the file /usr/bin/crontab before changing its file permission. Also note, after a package upgrade or reinstall, this change will be reversed to default.
please note the default permissions of /usr/bin/crontab file before any change:
# stat /usr/bin/crontab File: `/usr/bin/crontab' Size: 51784 Blocks: 104 IO Block: 4096 regular file Device: fd00h/64768d Inode: 1318020 Links: 1 Access: (4755/-rwsr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2017-09-13 09:39:27.192418684 +0530 Modify: 2016-07-22 12:50:39.000000000 +0530 Change: 2017-09-08 18:11:33.668586770 +0530
# crontab -e bash: /usr/bin/crontab: Permission denied
It is better to place cron job into /etc/cron.d
? Like:
$ cat /etc/cron.d/my
5 0 * * * user test -x /usr/bin/my && /usr/bin/my -cfg /etc/my.cfg
asked Dec 30, 2018 at 8:12
#!/bin/sh
# If started as root, then re-start as user "gavenkoa":
if [ "$(id -u)" -eq 0 ]; then
exec sudo -H -u gavenkoa $0 "$@"
echo "This is never reached.";
fi
echo "This runs as user $(id -un)";
# prints "gavenkoa"
exit 0;
answered Dec 30, 2018 at 11:48
1 gold badge36 silver badges60 bronze badges