Software Developer

Subscribe

© 2022

cron - How to set periodic tasks on Linux and macOS

Cron is a job scheduler in Unix-like computer systems. You can use it to set schedules for tasks, for example, every 5 minutes or every Monday at 4:23. Cron is most suitable for scheduling repetitive tasks.

Every user has it’s own crontab. You can check it with the following command:

crontab -l

To edit existing schedules use:

crontab -e

The above command launches your default text editor. You can specify jobs to run in separate lines.

# ┌──────────-── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12) OR jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
# | | | | |                                   OR sun, mon, tue, wed, thu, fri, sat
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute

Examples of usage


  1. Run task every day at 3 o’clock
    0 3 * * * /home/user/do_something.sh
    
  2. Run task every Saturday at 8:24
    24 8 * * 6 /home/user/do_something.sh
    
  3. Run task every 15 minutes, only on Wednesdays
    */15 * * * wed /home/user/do_something.sh
    
  4. Run task on Mondays, Tuesdays and Fridays at 9:45
    45 9 * * mon,tue,fri /home/user/do_something.sh
    
  5. Execute a cron twice a day - at 3:00 and 20:00
    0 3,20 * * * /home/user/do_something.sh
    
  6. Execute task every minute
    * * * * * /home/user/do_something.sh
    
  7. Execute a task every 30 seconds. It is not possible by cron parameters but you can use this workaround.
    * * * * * /home/user/do_something.sh
    * * * * *  sleep 30; /home/user/do_something.sh
    
  8. Predefined keywords (@yearly, @monthly, @weekly, @daily, @hourly, @reboot). You can use them to run task every year, month, week… and so on. Also, there is a possibility to run task every reboot (@reboot).
    @yearly /home/user/do_something.sh
    @monthly /home/user/do_something.sh
    @weekly /home/user/do_something.sh
    @daily /home/user/do_something.sh
    @hourly /home/user/do_something.sh
    @reboot /home/user/do_something.sh
    

Important tips before your first cronjob


Before setting the cronjob, make sure that the user has sufficient rights to execute it. You should also enter the full path to an application that will be launched.