Page 1 of 1

How to edit Crontab under Linux, MacOS X, QNAP, etc.

How to edit Crontab under Linux, MacOS X, QNAP, etc.
   5

In this article I’ll show you how you to edit the schedule of the job scheduler (Cron) on of your Linux/Unix based computer or NAS, for running certain tasks unattended.

Cron is a job scheduler and uses crontab, a relatively simple plain text file, as it’s configuration file.
In this file you can add, remove, or edit tasks you’d like to have run at particular dates, times, or intervals.

Please be aware that you’re doing this at your own risk …




Cron versus Crontab

Cron, which name is derived from the Greek word for time chronos, is a service or program that runs on most Linux/Unix like systems, to start particular unattended jobs or tasks at either a given date/time or a predefined particular interval.

For this a configuration file, crontab, holds a list of these tasks in a rather particular format.

So Cron is the service (or program) that starts the tasks or jobs, and Crontab is the “list” or time schedule of tasks for Cron to handle.

This means that if you want to add, remove or edit scheduled jobs, you’d only have to edit the crontab file.

Short Version

The short version of the story is this:

Edit crontab with crontab -e.

Or when you prefer to edit the file manually:

  1. Edit the crontab file with an editor like “VI” or “nano” (global: /etc/crontab  or /etc/config/crontab , or user: ~/.crontab ).
  2. Make cron aware of the changes with crontab /etc/config/crontab,  crontab /etc/crontab or crontab ~/.crontab.

 

On to the real detailed info …

Proceed at your own risk! 

Even though I should not have to say this, but please think before you do … proceed at you own risk!

Note:
– It is recommended to work with the crontab file on user level (typically ~/,crontab) if you can (not always an option on a NAS).
– Always make a backup of your crontab file before you start dabbling it … better safe than sorry.

Location of Crontab

The location of the crontab file, on most Linux systems, including Linux based NAS systems, is pretty straight forward. But, when you keep reading you might find that the location might not be all that important …

Linux based systems

First of all, in a multiuser environment we can say that there are two levels: Global (for the entire system) and User (for each individual) level.

Global is of course to be used for systemwide tasks, like for example collecting trash, etc.

Global/etc/crontab or /etc/config/crontab.

User level cron tasks are of course just for the individual user …

User specific~/.crontab

Network Attached Storage devices 

Keep in mind that the better NAS devices also run a Linux variation, like QNAP or Synology NAS devices.

For these devices, cron works as well although you’d probably stick to the global crontab and you’ll need to use an SSH connection to get to the command line (typically via “ssh admin@<NAS IP Address>” or through an application like PuTTY).

On a QNAP you will find the crontab at /etc/config/crontab.

QNAP recommend this approach to add items:

Add lines:
echo "1 4 * * * /share/custom/scripts/custom1.sh" >> /etc/config/crontab
echo "40 5 * * * /share/custom/scripts/custom2.sh" >> /etc/config/crontab

Restart Cron:
crontab /etc/config/crontab && /etc/init.d/crond.sh restart

MacOS X

MacOS X should be considered a Linux flavor as well – or more correct: a FreeBSD flavor – and uses Cron as well.

For the Mac however, a manually created global crontab, /etc/crontab,  might be removed automatically if you don’t use sudo touch /etc/crontab  before restarting.

The user specific file (~/.crontab) is said to work as usual.

Windows

Microsoft Windows does not use Cron, but does have a similar function onboard, the Windows Task Scheduler, which obviously isn’t compatible with cron or the use of crontab. However, if you’d like to use Cron under Windows, then look at free applications like CronW (might not support modern Windows versions) or PyCron,.

Editing Crontab

Differences in Cron Implementations 

There is a wide variety of Cron implementations out there, and they don’t all behave exactly the same.
Some options are not commonly supported, like adding a year parameter or the use of a question mark.

In this article we try to avoid these “special” options so if you’re looking for these special options, consult the manual of the developer or use in the shell the man statement:

man cron
man crontab

Opening Crontab

Crontab is a simple text file, which utilizes a sometimes confusing format to set date, time or interval, and can be edited with any plain text editor. My favorite used to be “VI“, until I discovered “nano“, both are available on most Linux like systems.

We can use a direct call to open the crontab file: nano /etc/crontab
Or we can use Crontab (recommended) to open the file by itself: crontab -e

The latter uses the default editor, and saves you the trouble of finding the crontab file.

“crontab -e” … Choose your own editor … 

The statement “crontab -e” often defaults to the use of “VI“, but why use “VI” if we can define our editor of preference by setting the EDITOR environment variable? I for one prefer the use of “nano” …

The way to do this depends on the shell you’re using …
Note that Bash is the most commonly used default shell on most Linux, FreeBSD and other Linux like systems like MacOS X.

Bashexport EDITOR=nano

C-Shellsetenv EDITOR nano

For some Cron versions, with BusyBox for example, the environment variable VISUAL should be set instead. See line 319 in the BusyBox code.
Keep in mind that Busybox is used in an aweful lot of devices: NAS boxes (like QNAP), Routers, Modem, Mobile devices, Satellite and cable boxes, etc.

Busyboxexport VISUAL=nano

Tip : The easiest way to find out which one works for you: simply execute the 3 statements one at a time followed by crontab -e  to see which editor opens.

Crontab Lines

Each line in the crontab represents such a job and the format of each line is build out of 6 or 7 parameters separated by spaces.

The optional value, the username, is placed between de “DayOfWeek” and “Command” parameters ensuring that the job is run as that user. But in all honesty – I have never used it (directly).

The first 5 are parameters related to the timing, followed by the optional username and the required file or statement(s) you’d like to execute, which can be a script or a program.

Tip : There are several so called “cron generators” online available. Although I have found that none of them is really good or complete, it might get you started building lines for your crontab. I found that the cron generator at EasyCron is probably one of the better ones.

Generic format:

Minutes   Hours   DayOfMonth   Month   DayOfWeek   Username   Command

Allowed Values
Parameter Values Alternative Notes
Minutes 0 – 59
Hours 0 – 23 Use military (24 hour) time!
DayOfMonth 0 – 31
Month 0 – 12 JAN – DEC
DayOfWeek 0 – 6 SUN – SAT 0 = Sunday, 6 = Saturday
Username Optional – Name of the user to execute the job as
Command Valid command line statement

As an illustration, the following example runs a backup script (/bin/backup.sh ) every night at 0:30 AM:


30 0 * * * /bin/backup.sh

Special Characters

In the example, you already see that certain special characters can be used to tweak the individual parameters.
The following special characters can be used for all time related parameters (so not for the command line):

Special Characters
Character Read as
* Asterisk Every (all)
/ Slash Step size (every)
, Comma And (list)
Hyphen/Minus To (range)
• Asterisk – Every (all)

When we use the “*” for example for the Month parameter, then the rule goes for “every month“.

Tip : A common mistake is to use “*” for example for Minutes, which will cause high system loads as the command is executed every minute.

• Slash – Step Size (every)

The “/” is useful for repeating patterns.

For example a value of */2 in the DayOfMonth parameter would mean that the command will run “every two days“.
Likewise, */5 in the Minutes parameter would mean that the command will run “every 5 Minutes“.

• Comma – And (List)

With the comma, we can provide a list …

For example 1,10,20 for DayOfMonth means that the command will be executed the “1st, 10th, and the 20th day of the month“.

• Minus or Hyphen – To (Range)

Of course making a list with individual items in it can be written shorter and this is where the minus or hyphen comes in.

When we enter 1-5 for DayOfWeek, the command will be executed on the “Days 1 to 5 of each week“, or in other words “Monday (1), Tuesday (2), Wednesday (3), Thursday (4) and Friday (5) of each week“.

Additional Special Characters (not for all parameters)

Besides the most common characters that we just discussed, some less used but practical characters. These however cannot be used in all parameters, unlike the previously presented special characters.

• Last

For DayOfMonth or DayOfWeek we can also use “L” which can be read as “Last“.

Example:
3L for the DayOfWeek means the “Last Wednesday of the Month“,
L for the DayOfMonth means the “last day of the month“.

• Nearest Week Day

DayOfMonth also allows “W” to indicate “Nearest week day“.

Example:
10W for DayOfMonth means “the weekday (business day) nearest to the 10th of the month“.
So if the 10th is a Sunday, the job will run on Monday the 11th, if the 10th is a Saturday, the job will run on Friday the 9th.

• Xth Weekday of the Month

DayOfWeek has the option to use a “#” (hash or pound) to indicate the “Xth weekday of the month“.
The # following a weekday number, must be followed by a number (0 – 5) indicating the occurance count of that weekday in a given month.

Example:
6#3 stands for the “the 3rd Friday (6 = Friday) of the month“.

• Newline or Carriage return

In the Command parameter, you can use a “%” as a “new line” (or carriage return) character (unless escaped with a slash).

A common mistake is that statements that already include a percent symbol should have it escaped as such: “\%“.
The percent symbol, if not escaped, will be seen as a carriage return!

Examples

As you might have seen in the previous examples, the numbers for the parameters and the special characters can be combined, and this is where we can achieve some really detailed timing or intervals.

We will illustrate the capabilities with a few examples:

Crontab Examples
Crontab line What it does
0 */2 * * * /bin/backup.sh Run backup.sh every day, on every even hour
0 1-23/2 * * * /bin/backup.sh Run backup.sh every day on every odd hour
We only use the hours 1 to 23 which makes it count only the odd hours.
*/15 * * * * /bin/backup.sh Run backup.sh every 15 minutes
0 */6 * * * /bin/backup.sh Run backup.sh every 6 hours
0 0 * * 2 /bin/backup.sh Run backup.sh at midnight on every Tuesday (2)
0 12 1-15,17,20-25 * * /bin/backup.sh Run backup.sh at noon on the 1st to 15th, the 17th, and the 20th till the 25th of each month
* 12 10-16/2 * * /bin/backup.sh Run backup.sh at noon on the 10th, 12th, 14th and 16th day of the month
* 12 10,12,14,16 * * /bin/backup.sh Is the same as the previous one: Run backup.sh at noon on the 10th, 12th, 14th and 16th day of the month
0 0 * * 0,6 /bin/backup.sh Run backup.sh at midnight on every weekend day (Sunday = 0 and Saturday = 6)
30 12 * * 1-5 /bin/backup.sh Run backup.sh every business day at 12:30 PM (Monday =1, Friday = 5)
0 5 1 */3 * /bin/backup.sh Run backup.sh every first day of the quarter (3 months) at 5 AM
0 0 22 10 * /bin/happybirthday.sh Run happybirthday.sh every year on Oct 22nd at midnight.

Predefined @ Statements

Cron also knows a few statements or abbreviations that might become in handy:

Cron abbreviations
 Abbreviation Meaning
@reboot Execute at reboot of your computer or when Cron restarts
@daily  Execute job every day at midnight
@midnight  Same as @daily – Execute a job everyday at midnight
@weekly  Execute job every Sunday at midnight
@monthly Execute job at the 1st day of the month at midnight
@yearly Execute job every January 1st at midnight of each year (Januari 1st)
@annually Same as @yearly

An example that runs /bin/backup.sh  every day at midnight:


@daily /bin/backup.sh 

Environment Variables

In Cron you can define some environment variables, but to minimize confusion I always stick to the default values.

These variables should be set in the first lines in crontab, so that Cron is aware of them when executing jobs.

Cron Variables
Variable Example Purpose
SHELL SHELL=/bin/bash Set the shell Cron should use
PATH PATH=/usr/bin:/bin:/usr/sbin Set the search path for Cron commands
HOME HOME=/ Set the home directory for Cron
MAILTO MAILTO=root Set who receives the output as an emal

Please eMail me the results

As you might have seen just now: Cron has the ability, in most implementations anyway, to send an email with the results.
To enable this add a first line like such:


MAILTO=root

Alternatively, depending on the Cron implementation, and email address can be used:


MAILTO="me@home.com"

Output – Dump it in a file or Mute it …

Output of an individual command/statement/script can also be redirected to a file.

In the example below, the script /bin/test.sh  is executed every day at midnight and the output is dumped in the file /etc/test.txt .


0 0 * * * /bin/test.sh > /etc/test.txt

Output can also be muted, meaning the output is thrown away.


0 0 * * * /bin/test.sh >/dev/null 2>&1

Additional Resources

http://www.unixgeeks.org

https://help.ubuntu.com

http://www.markus-gattol.name

http://www.easycron.com

http://en.wikipedia.org/wiki/Cron

http://wiki.gentoo.org/wiki/Cron

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are 5 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Nov 6, 2015 - 10:25 AM - Edward Blackburne Comment Link

    I should say up front that this comment is probably a bit of a rant. The most consistent characteristic of Linux instruction manuals, howtos etc. is that they usually cover all the options while, at the same time, leaving out the simple details which are essential to make the project work (surely everybody knows that). I like Linux. At this moment I have 4 PCs running Linux, but there are many basic Linux concepts I don’t quite understand. What brings me to this page is “sheduled tasks”. Most of my PC experience comes from Windows (3.11, 95, 98, XP and a bit of 7). Before that I used MSDOS (3.3, 4, 5, 6.2) and before that LDOS and TRSDOS., so I am familiar with the command line (mostly case insensitive). With some hesitation (Windows doesn’t do it that way), I created a crontab entry and it didn’t work. I don’t know why and I haven’t found a reason on this page. I also tried Gnome Schedule and it won’t let me create any entries. I don’t know why. I suspect that there is some sort of set up / initialisation / dependency which I have overlooked but I don’t know what that is. What I need is a howto which describes every step and requirement in a way that the average Windows user can understand. My specific requirement at this moment is to execute “xdotool key ctrl+r” at specified times. It should be easy but it isn’t. It would take me about 5 minutes to do something equivalent in Windows. Make that 2 minutes if it’s XP.

    Reply

    Edward Blackburne

    • Nov 7, 2015 - 3:21 AM - hans - Author: Comment Link

      Hi Edward,

      I couldn’t agree more … I love Linux but the sometimes too complex way of doing things or inconstancies amongst the different distro’s really do not make it “great” to work with or develop for. Like in your case: adding something to Cron should be much easier (not to mention the hard to remember notation). I’ve used numerous systems in my life, and Linux is for me the least user friendly environment (due to lack of good tools or proper explanation). 

      Depending on your system (unfortunately), you’d need to use “crontab -e”.

      Now to decypher what “code” you’d need, check out Crontab.Guru. It offers a great little online tool to determine what you need to enter for the timing part. For example: to run your statement every 2nd hour of the day use “0 */2 * * * xdotool key ctrl+r”.

      First problem you could run into is that cron can’t find xdotool, so you might have to enter the full path, for example “/usr/bin/xdotool”.

      Since I do not know if “xdotool key ctrl+r” by itself causes and issue or not, you could make a tiny script for that. The script should contain “xdotool key ctrl+r” and be marked as executable (chmod +x myscript.sh).

      I know debugging cron is a b*tch, I am really not a fan of it (until it works of course).
      If you’d like, you could consider using one or the other Cron GUI’s, for example Gnome Scheduler (works for Ubuntu).

      Reply

      hans

  • Nov 10, 2015 - 11:49 AM - Edward Blackburne Comment Link

    Some further comments.

    I hadn’t noticed that a runaway log file had filled up my system partition at just about the same time as I started to try out crontab. Having deleted the log file, crontab now functions as I originally expected using a line like 20 17 10 11 * ./send-ctrl-r.sh where “send-ctrl-r.sh” includes a command to append the current datetime to a log file for verification.

    There is a second problem. The command “xdotool key ctrl+r” doesn’t do what I want because cron runs it in the background. I revised the crontab line to 20 17 10 11 * DISPLAY=:0 xterm -e ./send-ctrl-r.sh so the script runs in the foreground and it now works as required.

    Reply

    Edward Blackburne

    • Nov 10, 2015 - 1:20 PM - hans - Author: Comment Link

      Hi Edward,

      thanks for posting these 2 tips – good tips for other that run into similar options. Especially the option to run a script in the foreground! 

      Thanks! 

      Reply

      hans

  • May 8, 2019 - 2:53 AM - ravikumar Comment Link

    Modify cron – scheduled entry – using bash script 

    1. change the scheduled time for a executable file/script in crontab.

    2. change the executable file for a scheduled time in crontab.

    Reply

    ravikumar



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.