Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Table of Contents

Configuración

Cron jobs are stored in a crontab file by username. These files are stored in Las tareas Cron se almacenan en un archivo crontab por usuario. Este archivo se alamacena en  /var/spool/cron/crontabs or  /var/spool/cron/. These files should not be edited directly. The crontab command should always be used to make changes.Este archivos NO se debe editar directamente. El comando crontab siempre se debe utilizar para realizar cambios.

Puede editar su crontab con el siguiente comandoYour crontab can be edited using the following command:

Code Block
languagetext
$ crontab -e

That command will open the crontab in a text editor where you can make the necessary changes. Saving the changes, and closing the file will install the new crontab.

Este comando abre el crontab en un editor de texto donde realizara los cambios necesarios. Guarde los cambios y cierre el archivo esto instalara el nuevo crontab.

El siguiente comando le permite visualizar los cambios realizados a su crontabThe following command will allow you to view your crontab without making changes:

Code Block
languagetext
$ crontab -l

The following command with remove your crontab entirelyEl siguiente comando remueve totalmente su crontab:

Code Block
languagetext
$ crontab -r

All of the above commands affects only the crontab for the user you are logged in as. That is, if you are logged in as myuser, you would only affect the crontab of myuser. If you are logged in as a privileged user (such as root), you can affect other users using the -u option. For example, the following command would edit the crontab for Todos los comandos anteriores afectan solo al crontab del usuario con el que inició sesión. Es decir, si ha iniciado sesión como myuser, solo afectaría al crontab de myuser. Si ha iniciado sesión como usuario privilegiado (como root), puede afectar a otros usuarios utilizando la opción -u . Por ejemplo, el siguiente comando editaría el crontab para myuser:


Code Block
languagetext
$ crontab -u myuser -e

The -u can be supplied with any of the other options used aboveLa opción -u se puede proporcionar con cualquiera de las otras opciones utilizadas anteriormente.

Syntax

A crontab file tells the Cron daemon what commands to run, and when to run them. It has three different kinds of lines: cron command, environment setting, and comment. Blank lines, leading spaces, and tabs are ignored.

Comments

Any line whose first non-whitespace character is a pound-sign (#) will be considered a comment. Inline comments are not allowed. Comments are not processed by the Cron daemon.

Environment Setting

Un archivo crontab le dice al Cron daemon qué comandos ejecutar y cuándo ejecutarlos. Tiene tres tipos diferentes de líneas: comando cron (cron command), configuracion del entorno (environment setting), y comentario (comment). Se ignoran las líneas en blanco, los espacios iniciales y las tabulaciones.

Comentarios

Cualquier línea cuyo primer carácter que no sea un espacio en blanco, sea un signo de almohadilla (#) se considerará un comentario. No se permiten comentarios en línea. Los comentarios no son procesados ​​por el Cron daemon.

Configuración del Entorno

La configuración del entorno esta en forma deEnvironment setting is in the form of:

Code Block
languagetext
name = value

Whitespace around the equal sign (=) are optional, and everything to the right of the equal sign is considered part of the value. The value can be quoted (with single or double quotes) to preserve leading or trailing spaces. Many environment variables are assigned a default value:

Los espacios en blanco alrededor del signo igual (=) son opcionales y todo lo que se encuentra a la derecha del signo igual se considera parte del valor. El valor se puede citar (con comillas simples o dobles) para conservar los espacios iniciales o finales. A muchas variables de entorno se les asigna un valor predeterminado:

  • SHELL se establece en SHELL is set to /bin/sh.
  • HOME and LOGNAME are set by  LOGNAME se establece en /etc/passwd.

SHELL and HOME can be overridden by environment settings, but LOGNAME can not.The MAILTO variable is checked to see if mail needs to be sent. By default, mail is sent to the owner of the crontab. Mail can be sent to another email address by assigning it to MAILTO. If you don't want Cron to send mail, assign MAILTO to the empty string HOME puede ser anulado por la configuración del entorno, pero no puede con LOGNAME.

La variable MAILTO se comprueba para ver si es necesario enviar el correo. de forma predeterminada, el correo se envía al propietario del crontab. El correo se puede enviar a otra dirección de correo electrónico asignándolo a MAILTO. Si no desea que Cron envíe correo, signe MAILTO. Si no desea que Cron envíe correo, asigne MAILTO a la cadena vacía (MAILTO=""). The MAILTO variable will only affect where emails are sent for commands that come after the line it is assigned. If you want to change all the email address of all commands, you would need to assign MAILTO at the top of the file. If you want to change the email address for a single command, you would set MAILTO directly above the command, and then set MAILTO back to its previous value before the next command.

Cron Commands

A cron command has six fields: five date and time fields, and a command field. The Cron daemon checks the schedule of each job every minute. A job is run whenever the time, and date matches the current time and date.

La variable MAILTO solo afectará a dónde se envían los correos electrónicos para los comandos que vienen después de la línea asignada. Si desea cambiar todas las direcciones de correo electrónico de todos los comandos, deberá asignar MAILTO en la parte superior del archivo. Si desea cambiar la dirección de correo electrónico para un solo comando, configuraría MAILTO directamente sobre el comando y luego restablecería MAILTO a su valor anterior antes del siguiente comando.

Cron Commands

Un comando cron tiene seis campos: cinco campos de fecha y hora, y un campo de comando. El Cron daemon verifica la programación de cada trabajo cada minuto. Un trabajo se ejecuta siempre que la hora y la fecha coincidan con la hora y la fecha actuales.

Un comando cron completo se verá asíA full cron command will look something like this:

Code Block
languagetext
0 0 * * * /path/to/command

Scheduling

The five date and time fields are minutehourday of the monthmonth, and day of the week respectivelyLos cinco campos de fecha y hora son minutoshorasdia del mesmes, y dia de la semana respectivamente:

Code Block
languagetext
┌───────────── minute
│ ┌───────────── hour
│ │ ┌───────────── day of the month
│ │ │ ┌───────────── month
│ │ │ │ ┌───────────── day of the week
│ │ │ │ │
│ │ │ │ │
│ │ │ │ │
* * * * *

Above diagram courtesy of Diagrama de arriba cortesía de Wikipedia.

FieldFilaAccepted ValuesValores aceptados
minuteminuto0-59
hourhora0-23
day of the monthdía del mes1-31
monthmes1-12 or names (see below)
day of the weekdía de la semana0-7 (Sunday is 0 or 7) or names

Los Cron jobs are run whenever the  minute se ejecutan siempre que los campos de minuto  hour , and  month  fields match the current time, and when  at least one of  the  day of the month , or  day of the year  fields matches.Names for days of the week, or months are the first three letters of a day or month (e.g Mon for Monday, Oct for October).

Note

Crons scheduled to run at times that can be "skipped" may result in jobs not running when you expect them to. A cron scheduled to run on the 31st of each month would only run during January, March, May, July, August, October, and November. If a daylight savings time change occurs, a cron job scheduled to run at a time that is skipped, or occurs twice will be skipped or be executed twice respectively.

All fields may contain an asterisk (*) which stands for any value.

Ranges are allowed, and are written as two numbers separated by a hyphen (-). Ranges are inclusive.

hora , y  mes coincidan con la hora actual, y cuando al menos uno de los campos de día del mes, o  día del año  los nombres de los dias de la semana o los meses son los primeros tres letras de un dia o mes (por ejemplo, Mon para lunes, Oct para Octubre).

Note

Los cron programados para ejecutarse en momentos que se pueden "omitir" pueden provocar que los trabajos no se ejecuten cuando se espera que lo hagan. Un cron programado para ejecutarse el 31 de cada mes solo se ejecutará durante enero, marzo, mayo, julio, agosto, octubre y noviembre. Si se produce un cambio de horario de verano, un trabajo cron programado para ejecutarse a una hora que se omite, o se produce dos veces, se omitirá o se ejecutará dos veces, respectivamente.

Todos los campos pueden contener un asterisco (*) que representa cualquier valor.

Los rangos están permitidos y se escriben como dos números separados por un guión (-). Los rangos son inclusivos.

Las listas están permitidas y son números o rangos separados por comas, p. Lists are allowed, and are numbers or ranges separated by commas e.g.  1,3,5,7 , or o 0-7,16-23.

Step values may be used with ranges. A step value is written as a range followed by a forward slash (/), and a number. The number will tell the Cron daemon how many times it should skip that job before running it again. The value 0-23/2 in the hour field tells Cron to execute the command every other hour. Step values may be used with asterisks as well so */2 will also tell Cron to run a command every other hour.

Commands

The last field of a cron command is the command to be run. Specifically, everything after the day of the week field until a newline or '%' character is considered to be part of the command, and will be executed by the shell set in the SHELL environment variable (/bin/sh by default).

All '%' characters in a command are converted to newline characters. A literal '%' must be escaped with a preceding backslash (\) e.g. \%. No other characters need to be escaped in a command.

Extensions

Los valores de paso se pueden usar con rangos. Un valor de paso se escribe como un rango seguido de una barra inclinada (/) y un número. El número le dirá al demonio Cron cuántas veces debe omitir ese trabajo antes de volver a ejecutarlo. El valor 0-23/2 en el campo de la hora le dice a Cron que ejecute el comando cada dos horas. Los valores de paso también se pueden usar con asteriscos, por lo que */2 también le indicará a Cron que ejecute un comando cada dos horas.


Comandos

El último campo de un comando cron es el comando que se ejecutará. Específicamente, todo lo que esté después del campo dia de la semana hasta una nueva línea o un carácter '%' se considera parte del comando, y será ejecutado por el shell establecido en la variable de entorno SHELL (/bin/sh por defecto).

Todos los caracteres '%' en un comando se convierten en caracteres de nueva línea. Un '%' literal debe ir acompañado de una barra invertida (\), por ejemplo \%. No es necesario escapar de otros caracteres en un comando.

Extensiones

Hay varias abreviaturas de tiempo especiales que se pueden usar en lugar de los cinco campos de fecha y horaThere are a handful of special time shorthand that may be used instead of the five date and time fields.

ShorthandValue
@rebootRuns once after a reboot.Ejecutar después de reinicio
@yearly or @annuallyRun once a year Ejecutar una vez al año (0 0 1 1 *).
@monthlyRun once a month Ejecutar una vez al mes (0 0 1 * *).
@weeklyRun once a week Ejecutar una vez a la semana (0 0 * * 0).
@dailyRun once a day Ejecutar una vez al dia (0 0 * * *).
@hourlyRun once an hour Ejecutar cada hora (0 * * * *).

Examples

Ejemplos

Un comando que se ejecuta cada minutoA command that runs every minute:

Code Block
languagetext
* * * * * /path/to/command

A command that runs every 5th minute on the hour (e.g. Un comando que se ejecuta cada minuto 5 (ejemplo. 1:05, 2:05, 3:05 etc.):

Code Block
languagetext
5 * * * * /path/to/command

A command that runs every 10 minutesUn comando que se ejecuta cada 10 minutos:

Code Block
languagetext
titleRange
0,10,20,30,40,50 * * * * /path/to/command

Un comando que se ejecute cada 6 minutos

Code Block
languagetext
titleStep
*/6 * * * * /path/to/command

A command that runs every Monday at Un comando que se ejecuta todos los lunes a las 8:00 AM:

Code Block
languagetext
0 8 * * 1 /path/to/command

A command that runs the first Tuesday of every month at Un comando que se ejecuta el primer martes de cada mes a las 5:30 PMp. m.:

Code Block
languagetext
30 17 1-7 * 2 /path/to/command

Output

As previously mentioned, the Cron daemon will email the output of the command to user's email address, or the address set by MAILTO whenever a cron job is executed. This can become a problem however if a command is run frequently. Stopping the emails is an option by setting MAILTO="", but you will then lose the output of the commands. Shell redirection can be used to have the output written to a file instead of being sent as an email.

Como se mencionó anteriormente, el  Cron daemon enviará por correo electrónico la salida del comando a la dirección de correo electrónico del usuario o a la dirección establecida por MAILTO cada vez que se ejecute un trabajo cron. Sin embargo, esto puede convertirse en un problema si un comando se ejecuta con frecuencia. Detener los correos electrónicos es una opción que se puede configurar como MAILTO="", pero luego perderá la salida de los comandos. La redirección de Shell se puede usar para que la salida se escriba en un archivo en lugar de enviarse como un correo electrónico.

El siguiente comando escribirá en un archivo de registro cada horaThe following command will write to a log file every hour:

Code Block
languagetext
0 * * * * echo "Hourly message." > message.log

The command that gets executed is El comando que se ejecuta es echo "Hourly message.". The remaining part of the line, > message.log, redirects the output to a file named message.log. It's important to note that this will replace whatever is in message.log with Hourly message. The >> operator will append to the end of a file instead of overwriting itLa parte restante de la línea, > mensaje.log, redirige la salida a un archivo llamado mensaje.log. Es importante tener en cuenta que esto reemplazará lo que esté en message.log con Hourly message. El >> operador agregará al final de un archivo en lugar de sobrescribirlo:

Code Block
languagetext
0 * * * * echo "Hourly message." >> message.log


If this cron job ran 3 times, the contents of message.log would look like thisSi este trabajo cron se ejecutó 3 veces, el contenido de message.log se vería así:

Code Block
languagetext
Hourly message.
Hourly message.
Hourly message.

If you don't care about the normal output of a cron job, and only want to be notified when it encountered an error, you can redirect the output to Si no le importa la salida normal de un trabajo cron y solo desea que se le notifique cuando encuentre un error, puede redirigir la salida a /dev/null.

Code Block
languagetext
0 * * * * /path/to/my/script > /dev/null

...

Note

/dev/null is a special device file in Linux (and other Unix-like operating systems) that is used when discard output. Anything that is written to this file just gets thrown away by the system.

Redirection can be used to prevent emails from being sent as well by sending both normal output and error messages to La redirección también se puede utilizar para evitar que se envíen correos electrónicos mediante el envío de mensajes de salida normales y de error a /dev/null instead of setting  configurado desde MAILTO="".

Code Block
languagetext
0 * * * * /path/to/my/script 2>&1 > /dev/null

2>&1 in short says to treat error messages like normal output. So  en resumen dice que trate los mensajes de error como una salida normal. Entonces 2>&1 > /dev/null can be read as "treat error messages like normal output, and throw away normal output se puede leer como "tratar los mensajes de error como una salida normal y desechar la salida normal".