Cron/es

En este artículo se describe como configurar y utilizar los demonios cron en Gentoo Linux.

¿Qué hace cron?
Cron is a daemon that runs scheduled tasks based on input from the command crontab. It accomplishes this task by waking up every minute and checking to see if there are any cron-jobs to run in any of the user crontabs.

El cron de facto
There are a few cron implementations for you to choose from in Portage. All of them offer a similar interface, namely the use of crontab 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.

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 que implementación quiere utilizar. 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 ofrece soporte para SELinux y PAM. Soporta menos plataformas que Dcron, pero más que Fcron.

Características de :


 * Support for SELinux;
 * Support for PAM ;
 * Setting of environment variables in crontabs (PATH, SHELL, HOME, etc.);
 * Each user can have a personal crontab; access is controlled by and

cronie
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  USE flag.

dcron (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 :


 * Fast, simple and free of unnecessary features;
 * Access to crontab is limited to the cron group, i.e. it doesn't rely on any external faculties.

fcron
Fcron pretende sustituir a vixie cron y 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 :


 * 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

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 :


 * Drop-in replacement for vixie-cron;
 * Multiprocess design;
 * Native daylight savings time support.

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.

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 it's job.

Optionally, if Fcron has not been installed, installing Anacron as a helper to the cron daemon might be a wise choice.

Again, do not forget to add acacron to the system's init process.

Crontab del sistema
The post install messages from some of these cron packages instruct the user to run crontab /etc/crontab. The file is the system crontab. A cron installation can use it in conjunction with to run the scripts in. Note that only vixie-cron and cronie schedule jobs in automatically. Dcron and fcron users will need to run crontab /etc/crontab every time they make changes to the 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.

A quick and easy way to comment out all the files in a file is by using the sed command. Run the following command to comment out all the lines in

Dar acceso a cron a usuarios en los que se confía
For users other than root to have access to the cron daemon, read this section, otherwise proceed to the next section: Scheduling cron-jobs.

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:

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 and  files. The most secure way to run a system is to first deny all users in, and then explicitly allow users in.

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

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

For example, to allow access to the user wepy, add him to as follows:

Planificar trabajos de cron
El proceso de editar los archivos crontab es distinto para cada paquete, pero todos soportan el mismo conjunto básico de órdenes: agregar y reemplazar crontabs, modificar crontabs, borrar crontabs y listar los trabajos en los crontabs. La siguiente lista muestra cómo ejecutar estas órdenes para cada paquete.

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.

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:

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.

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.

Los usuarios de anacron querrán modificar. Este fichero contiene cuatro campos: el número de días entre cada ejecución, el retraso en minutos después de cada ejecución, el nombre del trabajo y la orden a lanzar.

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

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.

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

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 again so that it looks like the following:

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.

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 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 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 emerge --sync run every day at 6:30 A.M., so make it look something like this:

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.

Usar cronbase
As mentioned earlier, all of the available cron packages depend on. The cronbase package creates, and a script called. Notice the default file contains something like this:

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.

Usar 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 similar to the following:

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.

Como nota final, es importante comentar cualquier entrada que se solape con otro cron instalado en el sistema, como en el siguiente ejemplo con la crontab de vixie-cron:

Si no se hace esto, las partes diarias, semanales y mensuales se lanzarán en momentos distintos tanto por el demonio cron como por anacron, conduciendo a posibles ejecuciones dobles de la tareas.

Notas finales
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 used.

¡Buena suerte!

Resolución de problemas
When having problems getting cron to work properly, this quick checklist might be helpful.

¿Está corriendo cron?
Run ps ax | grep cron to make sure it shows up in the process list.

¿Está funcionado cron?
Intente lo siguiente:

A continuación compruebe si se modifica periodicamente.

¿Están lanzándose sus órdenes?
Al igual que en el caso anterior pero redirija también la salida de errores:

¿Puede cron lanzar su tarea?
Revise los registros de cron en busca de errores, normalmente se encuentran en o en.

¿Hay algún fichero s?
cron usually sends mail when there is a problem; check for mail and look for the creation of a file.

Alternativas a Cron
Some hosting companies do not allow access to cron, but you can find a lot of cron jobs alternatives which are free or paid:


 * EasyCron