Cron/es

Esta guía describe como poner en marcha y utilizar cron.

¿Qué hace cron?
Cron es un demonio que ejecuta tareas de manera programada basado en la configuración de la orden. Cumple esta tarea despertando cada minuto y revisando la existencia de trabajos de cron en las crontabs de los usuarios.

El cron de facto
Existen varias implementaciones del gestor cron para escoger en Portage. Todas ofrecen un interfaz similar, el uso de la orden  o una orden parecida. Existe una herramienta relacionada llamada Anacron, que trabaja junto a cron en sistemas que no están encendidos de forma continua.

Vale la pena mencionar que los paquetes disponibles de cron dependen de. Este paquete técnicamente no aparece en las dependencias de los paquetes cron, pero ofrece la funcionalidad de tipo cron de la que la mayoría de los usuarios disfrutan.

Antes de comenzar a trabajar con cron, tendrá que elegir una implementación. Para facilitar la toma de esta decisión, abajo se resume información acerca de cada una.

Vixie cron
Vixie cron es un cron con muchas características, basado en el cron SysV. Cada usuario tiene su propio crontab y le está permitido especificar variables de entorno dentro de su crontab. A diferencia de las demás variantes de cron, también tiene soporte para SELinux y PAM. Soporta menos plataformas que Dcron, pero más que Fcron.

Características de :


 * Soporte para SELinux
 * Soporte para PAM
 * Definir variables de entorno en las crontabs (PATH, SHELL, HOME, etc.)
 * Cada usuario tiene su propia crontab, el acceso se controla mediante y

cronie
Cronie (sys-process/cronie) is a fork of vixie-cron done by fedora. 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 must be enabled through the anacron USE flag.

El cron de Dillon
Dcron pretende ser una implementación sencilla, elegante y segura de cron. No permite especificar variables de entorno en las crontabs y todos los trabajos cron se ejecutan desde. Al igual que Vixie cron, cada usuario tiene su propia crontab.

Características de :


 * Rápido, sencillo y sin características innecesarias
 * El acceso a  se limita al grupo cron, en otras palabras, no requiere capacidades externas

Fcron
Fcron pretende sustituir a Vixie cron y a Anacron. Su diseño toma en cuenta los sistemas que no están encendidos continuamente y está repleto de características adicionales. Tiene restricciones para iniciar los trabajos, control del orden de ejecución, la posibilidad de asignar valores "nice" (prioridades) a los trabajos y de ejecutar trabajos al arrancar el sistema. Eche un vistazo a la página oficial de fcron para obtener más información.

Características de :


 * Diseñado para funcionar en sistemas que no están constantemente encendidos, esto es, puede ejecutar una tarea después de reiniciar la máquina si no se ejecutó en el momento en el que estaba programada
 * Configuración de variables de entorno y muchas otras opciones en las crontabs
 * Cada usuario puede tener su propia crontab, el acceso se controla con los ficheros cron.allow y cron.deny
 * Sintaxis mejorada de crontab con soporte para muchas características nuevas

bcron
bcron es un sistema cron nuevo, diseñado para operar de manera segura. Para esto el sistema se divide en varios programas separados, cada uno responsable de una tarea distinta con comunicaciones estrictamente controladas entre ellas. El interfaz de usuario es un reemplazo exacto para programas similares (como vixie-cron), aunque la parte interna es muy diferente. Para más información vea la página de bcron en http://untroubled.org/bcron.

Características de :


 * Reemplazo exacto de vixie-cron
 * Diseño multiproceso
 * Soporte nativo de horario de verano

Anacron
Anacron no es un demonio cron, es una aplicación que funciona conjuntamente con uno. Ejecuta tareas a intervalos especificados en días y no asume que el sistema está encendido de manera continua. Ejecuta las tareas que no pudieron ejecutarse si el sistema estaba apagado. Anacron normalmente requiere un demonio cron para ejecutarlo diariamente.

Instalación
Elija la implementación de cron que prefiera e instálela.

Opcionalmente, si no ha instalado Fcron puede también instalar Anacron.

La crontab del sistema
Los mensajes que se indican después de la instalación de algunos de estos paquetes cron le informan de que debe ejecutar la orden. El fichero es la "crontab del sistema". Una instalación de cron lo usa junto a  para ejecutar los guiones que se encuentran en. Observe que solo Vixie-cron programa las tareas en de forma automática. Los usuarios de Dcron y Fcron deberán ejecutar  cada vez que hagan cambios a.

Por favor, observe que los trabajos programados en la crontab del sistema puede que no aparezcan en la lista de trabajos cron mostrados por.

Por supuesto, puede escoger no usar una crontab de sistema. Si escogió Dcron o Fcron, "no" ejecute. Si escogió vixie-cron, debe comentar todas las líneas de.

Giving trusted users access to cron
If you want users other than root to have access to the cron daemon, you'll want to read this section, otherwise, you can proceed to the next section, Scheduling cron-jobs.

No matter which cron package you use, if you want to allow a user to use crontab, he will first have to be in the cron group. As an example, if you wanted to add the user wepy to the cron group you would run:

If you're using dcron, that's all you have to do to give a user access to crontab. Dcron users may proceed to the next section Scheduling cron-jobs, all others will want to keep reading.

If you're using fcron, you'll want to edit and. The most secure way is to first deny everyone in, and then explicitly allow users in.

Permissions in fcron.deny

Now, say we have a user wepy who should be able to schedule his own cron-jobs. We would add him to as follows:

Permissions in fcron.allow

If you chose vixie-cron or cronie, you'll probably just want to edit.

For example, if you wanted to allow access to the user wepy, you would add him to as follows:

Permissions in /etc/cron.allow

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 you how to run those commands for each package.

Before we can use any of these commands though, you first need to understand the crontab itself. Each line in a crontab needs to specify 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 1, Sunday is 0 and 7). The days of the weeks 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, you will see that it is not as complicated as it sounds.

Examples

To test what we have just learned, let's go through the steps of actually inputting a few cron-jobs. First, create a file called and make it look like the this:

Now we can add that crontab to the system with the "new command" from the table above.

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

You should see a list resembling, if not, maybe you used the wrong command to input your new crontab.

This crontab should echo "I really like cron" every minute of every hour of every day every other month. Obviously you would only do that if you 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 you are using anacron, you should keep reading this section. Otherwise, proceed to the next section on Editing crontabs.

Anacron users will want to edit. 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  every 5 days, 10 minutes after anacron is started, you would have:

/etc/anacrontab

Anacron exits after all of the jobs in anacrontab are done, so if we want it to check these jobs every day, we will need to use cron. The instructions at the end of the next section tell you how to do that.

Editing crontabs
Let's be realistic though, you don't want your system telling you how much you like cron every minute. As a step forward, let's remove that crontab using the corresponding remove command from the table above. We will also list the cron-jobs after, just to make sure it worked.

You should see no cron-jobs in the output from. If you do see jobs listed, that means we failed to remove the crontab, and that you should make sure that you used the correct remove command for your cron package.

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

A real crontab

That would make cron run updatedb at 2:22 A.M. on Monday morning every week. You should now input the crontab with the proper new command from the table above, and check the list again.

Now let's say that you also want to add  to your daily schedule. You could do this by first editing and then using   just as we did before, or you could use the proper edit command from the table above. This gives you a way to edit your user's crontab in situ, without depending on external files like.

That should open your user's crontab with an editor. We want to have  run every day at 6:30 A.M., so we'll make it look something like this:

A real crontab

Again, check the cron-jobs list as we did in the previous examples to make sure the jobs are scheduled. If they are all there, then you're all set.

Using cronbase
As mentioned earlier, all of the available cron packages depend on. The cronbase package creates, and a script called. You might have noticed that the default contains something like this:

Default system crontab

To avoid going into much detail, we can just assume that these commands will effectively run your hourly, daily, weekly and monthly scripts. This method of scheduling cron-jobs has some important advantages:


 * They will run even if your computer was off when they were scheduled to run
 * It is easy for package maintainers to place scripts in those well defined places
 * You know exactly where your cron-jobs and your crontab are stored, making it easy for you to backup and restore this part of your system

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,, is usually like the following:

As you see 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.

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:

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.

Final Notes
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 what you use.

Good luck!

Troubleshooting
If you're having problems getting cron to work properly, you might want to go through this quick checklist.

Is cron running?
Run  and make sure it shows up!

Is cron working?
Try the following:

crontab to see if cron is running

Then check if is modified periodically.

Is your command working?
Same as before, but perhaps redirect the standard error output as well:

crontab to verify application runs

Can cron run your job?
Check the cron log, usually or  for errors

Are there any s?
cron usually sends mail when there's a problem; check your mail and also look for.

Acknowledgements
We would like to thank the following authors and editors for their contributions to this guide:


 * Eric Brown
 * Xavier Neys
 * nightmorph