...
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
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
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 | ||
|---|---|---|
| ||
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:
SHELLse establece enSHELLis set to/bin/sh.HOMEandLOGNAMEare set by yLOGNAMEse 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 y 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 | ||
|---|---|---|
| ||
0 0 * * * /path/to/command |
Scheduling
The five date and time fields are minute, hour, day of the month, month, and day of the week respectivelyLos cinco campos de fecha y hora son minutos, horas, dia del mes, mes, y dia de la semana respectivamente:
| Code Block | ||
|---|---|---|
| ||
┌───────────── minute │ ┌───────────── hour │ │ ┌───────────── day of the month │ │ │ ┌───────────── month │ │ │ │ ┌───────────── day of the week │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ * * * * * |
Above diagram courtesy of Diagrama de arriba cortesía de Wikipedia.
| FieldFila | Accepted ValuesValores aceptados |
|---|---|
| minuteminuto | 0-59 |
| hourhora | 0-23 |
| day of the monthdía del mes | 1-31 |
| monthmes | 1-12 or names (see below) |
| day of the weekdía de la semana | 0-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.
| Shorthand | Value |
|---|---|
@rebootRuns once after a reboot. | Ejecutar después de reinicio |
@yearly or @annually | Run once a year Ejecutar una vez al año (0 0 1 1 *). |
@monthly | Run once a month Ejecutar una vez al mes (0 0 1 * *). |
@weekly | Run once a week Ejecutar una vez a la semana (0 0 * * 0). |
@daily | Run once a day Ejecutar una vez al dia (0 0 * * *). |
@hourly | Run once an hour Ejecutar cada hora (0 * * * *). |
Examples
Ejemplos
Un comando que se ejecuta cada minutoA command that runs every minute:
| Code Block | ||
|---|---|---|
| ||
* * * * * /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 | ||
|---|---|---|
| ||
5 * * * * /path/to/command |
A command that runs every 10 minutesUn comando que se ejecuta cada 10 minutos:
| Code Block | ||||
|---|---|---|---|---|
| ||||
0,10,20,30,40,50 * * * * /path/to/command |
Un comando que se ejecute cada 6 minutos
| Code Block | ||||
|---|---|---|---|---|
| ||||
*/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 | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
0 * * * * /path/to/my/script > /dev/null |
...
| Note |
|---|
|
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 | ||
|---|---|---|
| ||
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".