Cron & crontab, explained

Lucain published a while ago excellent tutorial on cron and crontab that I think is worth sharing. Cron is a kind of equivalent to Scheduled Tasks in Windows, only that it is handled from the terminal. Those who prefer a visual interface to achieve the same goal, can see this Another item.

What is cron?

The name cron comes from the Greek chronos which means "time". In the Unix operating system, cron is a regular background process manager (daemon) that runs processes or scripts at regular intervals (for example, every minute, day, week, or month). The processes that must be executed and the time at which they must be executed are specified in the crontab file.

How does it work

The cron daemon starts from /etc/rc.d/ o / Etc / init.d depending on the distribution. Cron runs in the background, checks the crontab task table every minute / etc / crontab or in / var / spool / cron in search of tasks to be accomplished. As a user we can add commands or scripts with tasks to cron to automate some processes. This is useful for example to automate the update of a system or a good backup system.

Related article:
Tutorial: Install .tar.gz and .tar.bz2 Packages

What is Crontab?

Crontab is a simple text file that stores a list of commands to be executed at a time specified by the user. Crontab will check the date and time when the script or command should be executed, the execution permissions and it will do it in the background. Each user can have their own crontab file, in fact the / etc / crontab it is assumed to be the root user's crontab file, when normal users (and even root) want to generate their own crontab file then we will use the crontab command.

Crontab is the easiest way to manage cron tasks on multi-user systems, either as a simple system user or root user.

Using crontab

We are starting with a simple example.

We are going to automate the update of a system, to eliminate the annoying of "I always have to update and I don't like that!"

Related article:
Commands to know the system (identify hardware and some software configurations)

First of all we will make a script. This script will be called by cron and will contain all the instructions we want it to do, therefore it is necessary to test it in several cases and in several ways before including it in cron, a simple update script like this:

#! / bin / bash #script update example #choose your distribution # debian-ubuntu # apt-get update & apt-get -y upgrade #fedora #yum -y update #Arch #pacman --noconfirm -Syu

Remove the # from your distro line. In case it's Ubuntu / Debian, it starts with apt-get.

We save the script as update.sh (eg scripts directory your home). We change the execution permissions of the said script with:

chmod a + x ~ / scripts / update.sh

We execute the script a couple of times to verify that everything runs smoothly, we modify what is necessary (it must not contain errors, otherwise cron will only repeat an error over and over again). Now to add the task to our crontab.

Add tasks to crontab

We execute the edition of the crontab with crontab -e, in some distros (such as Ubuntu) it gives us the option to choose the text editor we want, the rest we are left with vi. The crontab file will look something like this.

# mh dom mon dow user command

where:

  • m corresponds to the minute the script will be executed, the value ranges from 0 to 59
  • h the exact time, the 24-hour format is handled, the values ​​range from 0 to 23, with 0 being 12:00 midnight.
  • sun refers to the day of the month, for example you can specify 15 if you want to run every 15 days
  • dow means the day of the week, it can be numeric (0 to 7, where 0 and 7 are Sunday) or the first 3 letters of the day in English: mon, tue, wed, thu, fri, sat, sun.
  • user defines the user who will execute the command, it can be root, or a different user as long as they have permissions to execute the script.
  • command refers to the command or the absolute path of the script to be executed, example: /home/usuario/scripts/update.sh, if it does call a script it must be executable

To be clear a few examples of cron tasks explained:

15 10 * * * user /home/usuario/scripts/update.sh

It will run the update.sh script at 10:15 am every day

15 22 * * * user /home/usuario/scripts/update.sh

It will run the update.sh script at 10:15 pm every day

00 10 * * 0 root apt-get -y update Root user

It will run an update every Sunday at 10:00 am

45 10 * * sun root apt-get -y update

Root user will run an update every Sunday (Sun) at 10:45 am

30 7 20 11 * user /home/usuario/scripts/updata.sh

On November 20 at 7:30 the user will run the script

30 7 11 11 sun user /home/usuario/scripts/pastel_con_velitas.sh

On November 11 at 7:30 am and that is Sunday, the user will celebrate his sysadmin (that is, me)

01 * * * * user /home/user/scripts/molestorecordatorio.sh

An annoying reminder every minute of every hour every day (NOT recommended).

They can still be handled special ranges:

30 17 * * 1,2,3,4,5

At 5:30 in the afternoon every day from Monday to Friday.

00 12 1,15,28 * *

At 12 noon every first, fifteenth and 28th of each month (ideal for payroll)

If this is confusing, crontab handles special strings to define these ranges.

@reboot Run once, at startup
@yearly runs only once a year: 0 0 1 1 *
@annually same as @yearly
@monthly runs once a month, the first day: 0 0 1 * *
@weekly Weekly the first minute of the first hour of the week. 0 0 * * 0 ″.
@daily daily, at 12:00 A.M. 0 0 * * *
@midnight same as @daily
@hourly at the first minute of every hour: 0 * * * *

Its use is very simple.

@hourly user /home/user/scripts/molestorecordatorio.sh @monthly user /home/user/scripts/backup.sh @daily root apt-get update && apt-get -y upgrade

Last but not least:

Cron job management

crontab file

Replace the existing crontab file with a user-defined file

crontab -e

Edit the user's crontab file, each new line will be a new crontab task.

crontab -l

List all the user's crontab tasks

crontab -d

Delete the user's crontab

crontab -c dir

Defines the user's crontab directory (this must have the user's write and execute permissions)

crontab -u user

prefix to handle another user's crontab, examples:

$ sudo crontab -l -u root $ sudo crontab -e user2 #crontab -d -u user

This tool, like many others, can be seen in more depth and in more detail in:

Thanks Lucain!

The content of the article adheres to our principles of editorial ethics. To report an error click here!.

48 comments, leave yours

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   Alvaro Ortiz said

    Ugh… a bit confusing.

  2.   tonic said

    * / 30 is missing (in the minutes field) that runs every 30 minutes ...

    1.    erm3nda said

      Just this I was going to comment until I decided to review the comments 😀
      This modifier is a very important piece of information and something very useful.

      1.    KIKA said

        Hello!
        Right now I am testing a configuration every 45 minutes.

        * / 45 * * * *, and the instruction is executed at 45 minutes of every hour AND every hour. That is to say:

        It runs at 3:45, then 4:00, 4:45, then 5:00, 5:45, 6:00, 6:45, and so on.

        I have something wrong? What can I do so that it is only every 45 minutes, or at least once at 45 minutes every hour.

    2.    KIKA said

      Hello!
      Right now I am testing a configuration every 45 minutes.

      * / 45 * * * *, and the instruction is executed at 45 minutes of every hour AND every hour. That is to say:

      It runs at 3:45, then 4:00, 4:45, then 5:00, 5:45, 6:00, 6:45, and so on.

      I have something wrong? What can I do so that it is only every 45 minutes, or at least once at 45 minutes every hour.

  3.   Slack said

    Hello super useful the information to clarify how cron works.
    Bytes

  4.   Slack said

    for *

  5.   Hunter said

    Excellent, thanks for clarifying how cron works .. let's put a bit of hand 🙂

  6.   Jacob said

    This line as I understand it will be executed at 10:15 pm, correct me if I am wrong
    Well there it says 10:15 am
    15 22 * * * user /home/usuario/scripts/update.sh

  7.   Agustin said

    Hello! very good info.
    To execute a Script every half hour, the line that should be added to CronTab would be: "30 * * * * root Scrip.sh" Correct? Thank you so much!

  8.   let's use linux said

    No. If I remember correctly, for that you have to put / 30 * * * * root Scrip.sh.
    That is, add the / before 30.
    Cheers! Paul.

  9.   Jonathan said

    Hello I liked your post, it is very complete but I wanted to ask you something.
    I'm having problems with this command and one like "at".

    I want to run a script at a certain time and put

    at -f /home/mi_user/Desk/script.sh 18:08 example

    and the script is not executed on the screen, that is, in the terminal, is it executed in the background?

    And with cron the same thing happens to me, I edit the crontab file with "crontab -e"

    at the end I add this line:

    46 19 my_user /home/mi_user/Desk/script.sh

    and it does nothing, it does not show the script.

    Any suggestion? Thank you very much and apologize for any inconvenience

    1.    let's use linux said

      For the terminal to appear, you may have to run the terminal and pass the script as a parameter.

      For example:

      lxterminal -e "my_user /home/my_user/Desk/script.sh"

      The parameter to use may vary based on the terminal emulator you use.

      I hope it works.

      Hug! Paul.

  10.   patretcas said

    Contribution is appreciated.

    10 points !!

    salu2 !!

  11.   Rodolfo said

    Thank you very much, it helped me a lot to clarify some things, total thanks, for more details or questions I will go to the MAN PAGE, reiterated greetings.

  12.   jahir said

    man thank you very much, I have been reading and testing the examples. thank you very much ... it's very understandable. Cheers

  13.   Geovanni said

    I used ubuntu Server 12.04.2 LTS, and the version of crontab that I have, to delete the list of the user's jobs is used, crontab -r (and -l, as this manual says). Sure it is by question of versions.

    On the other hand, I once ran only crontab and this kind of let me create my own execution file, but this was not the one that was being executed. The one that runs is the one in / etc / crontab. maybe someone will use the comment.

    PS (I searched with locate and whereis crontab but it only returned the aforementioned address and another file that is encrypted, so if the one that was executed was the one in / etc / crontab, but when executing the crontab -e command, mine would appear with all the jobs that I had defined) where was this file being stored '???? Regards. I always log in with root.

  14.   Sebastian said

    Excellent, very useful !!!

  15.   mmm said

    Hello, I would like to do this ………… «15 10 * * * root ifdown eth0»

    that is to say that at a certain time the network card is turned off ………… well, I put it in the crontab and it didn't work …… .. what's up?

    Saludos y gracias

  16.   Miguel said

    You missed defining "mon" after the title "Add tasks to crontab"

    The article is still nice, cron is extremely useful.

  17.   OScar said

    How cool was that good post, ask me
    If I want to keep track of the records left by the execution of tasks, where can I see it?

    is decdir I want to see the history of the actions made in the past of this file and I want to see who has modified it and the date

    Thank you

  18.   oscar said

    I want to check the modification history of this

    how can I do it

    Thank you

  19.   Andres Ledo said

    Good morning,

    I think that in the ubuntu script you have made a mistake, you have put ap-get -y upgrade instead of apt-get -y upgrade. (You have left a t).

    A greeting.

    1.    let's use linux said

      So is. Thank you!
      Hug! Paul

  20.   Gabriel said

    I want to know how to create a cron file to be able to specify the time each when it is executed, the directory, etc.

  21.   Valentin said

    Thanks for clarifying the operation and the basic commands for cron, now to entertain yourself for a bit.

  22.   Sander said

    Whenever I look for information on any topic related to Gnu / Linux, I go round and round to always find in 90% of the cases the best tutorial in this great community, I think that from now on I will start here and then elsewhere.

    regards

    1.    let's use linux said

      Thanks Sander! A hug! Paul.

  23.   daryo said

    dom = day of month
    dow = day of week
    it's easier if you associate

  24.   Paschal said

    Thank you very much, very complete and well explained.

  25.   Maxillia said

    This is the same thing that my OS teacher gave us, I don't change anything, now I see why the class is so bad .-. Well, this is the same as homework xD

  26.   Marcelo said

    Dear User,

    Query, can the duration time of a task be limited?
    For example I have a task that is repeated every 5 minutes, on repetition if this task is still active, kill it and run again.

    Thank you,
    Marcelo.-

    1.    let's use linux said

      Hello, Marcelo!

      I think it would be better if you ask this question in our question and answer service called Ask FromLinux so that the whole community can help you with your problem.

      A hug, Pablo.

  27.   aj said

    good post.
    What is the command per terminal to add tasks to the crontab (without entering the crontab and adding them manually with 'crontab -e' or replacing the crontab with another crontab with 'crontab file').
    The idea is to create an external script to add the tasks to the crontab
    Thank you

    1.    David said

      it seems to me that you could use 'echo' whatever you want to add '| cat >> 'cronotab path (/ etc / cronotab)' «

  28.   Rafael Vera said

    How would an expression run every 3 days exactly

  29.   José Antonio said

    Hey.

    I have a problem executing a cron job.

    I run the following task with cronta -e:

    01 * * * * root /home/user/script/mfile.sh

    but the task is not done. I have checked that myfile.sh has execution permission and that the user who executes it is root.

    I run the same task in / etc / crontab and after restarting the service, it doesn't work for me either.
    The content of myfile.sh is a command that updates a DB and if I run it in the console it works.
    any idea what the problem may be?

    1.    Fredd said

      The database user may not have all the permissions and you will first have to export the environment variables from your database engine.
      For example in db2 this line would go to the beginning of the script
      . / home / db2inst1 / sqllib / db2profile

      Another cause could be that the script requires connection to the database, make the connection to the database within the script

  30.   LA3 said

    I did not know that I had to restart the crond, I had been fighting with this for a while

  31.   kenia said

    They will know how to indicate that the task is run every end of the month, at the time indicated .. the detail is that I cannot achieve how I know that it takes the last day of each month .. ??? I had to write them down one by one but when the end of the month of February comes that it is biciesto it is complicated for me ..

  32.   Jesus said

    good day!!

    How do I stop the process that is being executed in the crontab?

  33.   Jesus said

    process * …………

  34.   Julianna said

    Could it be that you can help me? eu tenho um script by minha authored that does not work no crontab! jб dei all the permissхes, not a specific cron or user that can execute it-most nothing happens! I would like to know if you can help me, some other things work no cron! Vlws

  35.   Anthox said

    How would you put a task to run every last day of the month (days: 31-30-28)?

  36.   tfercho said

    As you know, the su command is used to change user in a console. If I use the command su thus: "your user" change user but without the proper settings of "user", if I run su as: "su - user" change user by loading the user settings. With cron I indicate the user, but how do I load the configurations of this user?

  37.   Rob said

    And if I want to stop it?

  38.   Regi said

    Hello,
    I don't know what I'm doing wrong, but I follow the steps and nothing is executed. I have tried:
    59 * * * * / usr / bin / gedit
    * * * * * / usr / bin / gedit
    * * * * * root / usr / bin / gedit
    * * * * * usr / bin / test.sh
    * * * * * root usr / bin / test.sh

    and nothing at all. It does not execute anything. I have rebooted and everything.

  39.   Ferqos said

    thank you very much