Cron

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Cron and the translation is 19% complete.

Outdated translations are marked like this.
Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎italiano • ‎русский • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Resources

Dieser Leitfaden beschreibt, wie Sie cron einrichten und verwenden können.

Cron Grundlagen

Was cron macht

Cron ist ein Hintergrunddienst, der geplante Aufgaben, die durch das Kommando crontab eingerichtet wurden, abarbeitet. Er erledigt diese Aufgaben, indem er jede Minute aufwacht und überprüft ob es einen Cron-Job gibt, der ausgeführt werden muss.

Hinweis
Beachten Sie das "crontab" der Name einer Liste von Cron-Jobs sowie der Name für das Kommando zum editieren dieser Liste ist.

Der tatsächliche Cron

Es gibt einige Cron-Implementierungen, in Portage, aus denen Sie wählen können. Jeder dieser Implementierungen stellt die gleiche Schnittstelle, meistens crontab genannt, bereit. Außerdem gibt es eine Implementierung names Anacron, welche für Systeme gedacht ist, die nicht ununterbrochen laufen.

Es ist auch erwähnenswert, das alle Cron-Pakete vom paket sys-process/cronbase abhängig sind. Dies ist technisch nicht notwendig, bietet aber Cronähnliche Funktionen die die meisten Nutzer zu schätzen wissen.

Bevor wir anfangen mit Cron zu arbeten, müssen Sie sich entscheinden, welche Implementierung Sie nutzen möchten. Der Einfachheit halber, haben wir einige Informationen zu jeder Implementierung zusammengestellt.

Welcher Cron ist der richtige für mich?

Notiz
Emerge virtual/cron to install Gentoo's default cron implementation.

vixie-cron

Vixie-cron ist eine voll ausgestattet Cron-Implementierung, die auf dem SysV-Cron basierd. Jeder Benutzer hat seinen eigenen crontab und es ist erlaubt eigene Umgebungsvariablen inerhalb des crontabs zu erstellen. Im Gegensatz zu den anderen Cron-Implementierungen stellt Vixie-Cron Unterstützung für SELinux und PAM bereit. Vixie-Cron unterstütz weniger Architekturen wie Dcron aber mehr wie Fcron.

Funktionen von sys-process/vixie-cron:

  • Unterstützung von SELinux
  • Unterstützung von PAM /etc/security/limits.conf
  • Setzen von Umgebungsvariablen in crontabs (PATH, SHELL, HOME, usw.)
  • Jeder Benutzer kann seinen eigenen crontab erstellen; der Zugriff wird übercron.allow und cron.deny gesteuert

cronie

Cronie (sys-process/cronie) ist eine Abspaltung von vixie-cron, die von Fedora erstellt wurde. Da es eine Abspaltung ist, hat cronie die gleichen Funktionen wie vixie-cron. Zusätzlich kommt cronie mit einer anacron-Implementierung, die mit der USE-Flag "anacron" aktiviert werden muss.

dcron (Dillon's Cron)

Dcron bietet eine einfache, elegante und sichere Implementierung von cron. Es ist nicht erlaubt Umgebungsvariaben in crontabs zu nutzen und alle Cron-Jobs werden von /bin/sh ausgeführt. Wie bei vixie-cron hat jeder Benutzer seinen eigenen crontab.

Funktionen von sys-process/dcron:

  • Schnell, einfach und frei von unnötigen Funktionen
  • Zugriff auf crontab ist limitiert auf die cron-Gruppe

fcron

Fcron Ziel ist es, vixie-cron und anacron zu ersetzen. Es wurde für Systeme entworfen, die nicht ständig laufen und es ist vollgepackt mit extra Funktionen. Es bietet Aufgaben-Starteinschränkungen, Aufgaben-Serialisierungs-Steuerelemente, die Fähigkeit nice-Werte an Aufgaben zu vergeben und die Fähigkeit Aufgaben beim Systemstart auszuführen. Lesen Sie fcron's home page für mehr Informationen.

Funktionen von sys-process/fcron:

  • Für Systeme entwickelt, die nicht kontinuierlich laufen, d.h. es kann eine Aufgabe dem Einschalten starten, die nicht ausgeführt wurde, als das System ausgeschaltet war.
  • Setzen von Umgebungsvariablen und viele andere Optionen in crontabs
  • Jeder Benutzer kann seinen eigenen crontab erstellen; der Zugriff wird übercron.allow und cron.deny gesteuert
  • Erweiterter crontab-syntax mit Unterstützung vieler neuer Funktionen

bcron

Bcron ist ein neues cron-System, das mit dem Sicherheitsgedanken im Vordergrund entworfen wurde. Um dies zu erreichen, ist das System in mehrere eigenständige Programme aufgeteilt. Jedes Programm ist für eine Aufgabe zuständig und die Kummunikation untereinander ist streng kontrolliert. Die Benutzeroberfläche ist ein direkter Austausch für ähnliche Systeme (wie vixie-cron), aber das interne unterscheidet sich stark. Für mehr Informationen, schauen Sie sich die bcron's Homepage an.

Funktionen von sys-process/bcron:

  • Austausch für vixie-cron
  • Multiprocess design
  • Eingebaute Sommerzeit-Unterstützung

anacron

Anacron ist kein Cron-Hintergrunddienst. Es arbeitet in funktionen mit einem Cron-Hintergrunddienst zusammen. Es führt Kommandos in festgelegten Tagesintervallen aus und setzt nicht vorraus, das das System kuntinuierlich läuft. Es führt Aufgaben später aus, wenn das System zur Ausführungszeit ausgeschaltet war. Anacron greift normal auf einen Cron-Hintergrunddienst zurück um seine Aufgaben jeden Tag auszuführen.

Cron benutzen

Installation

Wählen Sie die Cron-Implementierung die Ihnen am meisten zusagt und emergen Sie diese.

root #emerge --ask dcron
root #/etc/init.d/dcron start
root #rc-update add dcron default

Wenn Sie nicht Fcron installiert haben, können Sie optional noch Anacron installieren.

root #emerge --ask anacron
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 by default. If that isn't the case though, then it can still be launched through manual definitions:

DATEI /etc/crontabLaunching 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

System crontab

The post install messages from some of these cron packages instruct the user to run crontab /etc/crontab. The /etc/crontab file is the system crontab. A cron installation can use it in conjunction with sys-process/cronbase to run the scripts in /etc/cron.{daily,hourly,weekly,monthly}. Note that only vixie-cron and cronie schedule jobs in /etc/crontab automatically. Dcron and fcron users will need to run crontab /etc/crontab every time they make changes to the /etc/crontab file.

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

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

root #sed -i -e "s/^/#/" /etc/crontab

Giving trusted users access to cron

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

Notiz
Giving another user access to crontab does not let him run cron-jobs as root. For a user to be able to edit the root crontab, look into using sudo (app-admin/sudo). Please read the Gentoo Sudo(ers) Guide for more details.

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

root #gpasswd -a wepy cron
Notiz
When adding a user to the cron group, make sure that the user logs out and logs back in for the group change to take effect.

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

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

Wichtig
If neither /etc/fcron/fcron.allow nor /etc/fcron/fcron.deny exist then all users in the cron group will be allowed to use crontab. fcron comes with a default fcron.allow which allows all users in the cron group access to fcrontab.
CODE Permissions in fcron.deny
all

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

CODE Permissions in fcron.allow
wepy

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

Wichtig
It is important to note that if only /etc/cron.allow exists, then only the cron group users listed there will have access. Otherwise, if only an empty /etc/cron.deny exists, then all cron group users will be allowed. Do not leave an empty /etc/cron.deny if no /etc/cron.allow file exists!

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

CODE Permissions in /etc/cron.allow
wepy

Scheduling cron-jobs

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

Version Edit crontab Remove crontab New crontab List cron-jobs
dcron crontab -e crontab -d [user] crontab file crontab -l
fcron fcrontab -e fcrontab -r [user] fcrontab file fcrontab -l
vixie-cron, cronie & bcron crontab -e crontab -r -u [user] crontab file crontab -l
Notiz
When using the remove command, if no argument is supplied, it deletes the current user's crontab.
Notiz
Fcron also has a symlink from crontab to fcrontab.

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

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

CODE Examples
# 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
Notiz
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 crons.cron and make it look like the this:

DATEI crons.cronCreate 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.

root #crontab crons.cron
Notiz
The output from the echo commands will not be seen unless redirection is used.

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

root #crontab -l

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

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

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

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

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

DATEI /etc/anacrontab
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.

Editing crontabs

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

root #crontab -d
root #crontab -l

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

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

CODE 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

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

root #crontab -e

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

CODE 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.

Using cronbase

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

CODE 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.
Notiz
Again, it is useful to point out that vixie-cron, cronie and bcron automatically read /etc/crontab, while dcron and fcron do not. Please read the System crontab section to learn more about this.

Using anacron

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

DATEI /etc/anacrontab
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 /var/spool/anacron and calculate if the corresponding entry in the configuration file has expired since the last run. If it has, then the command is invoked again.

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

DATEI /etc/crontab
# for vixie-cron
# $Header: /var/cvsroot/gentoo-x86/sys-process/vixie-cron/files/crontab-3.0.1-r4,v 1.3 2011/09/20 15:13:51 idl0r Exp $
  
# 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.


Troubleshooting

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

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

Is cron running?

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

root #ps ax | grep cron

Is cron working?

Try the following:

CODE crontab to see if cron is running
* * * * * /bin/echo "foobar" >> /file_you_own

Then check if /file_you_own is modified periodically.

Is the command working?

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

CODE crontab to verify application runs
* * * * * /bin/echo "foobar" >> /file_you_own 2>&1

Can cron run the job?

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

Are there any dead.letters?

cron usually sends mail when there is a problem; check for mail and look for the creation of a ~/dead.letter 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 (/var/spool/mail) mails, by enabling the mbox useflag with the respective package which provides the MTA.

Cron Jobs Alternatives

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

  • EasyCron
    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, Joshua Saddler (nightmorph)
    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.