Content
Overview
When it comes to running Linux systems, automation plays a key role in increasing efficiency and reliability. There are many tasks that we don't want to or can't do manually every time: for example, making daily backups, deleting temporary files, running system check scripts, or even checking for software updates. Cron was created to perform these and similar repetitive tasks on a scheduled basis.
Cron can be best thought of as a built-in, reliable personal assistant for the Linux system, which does its job based on a predefined calendar, day and night, without human intervention. The heart of the system consists of two main components: on the one hand, a constantly running in the background cron from a daemon (service), which plays the role of the "alarm clock", and on the other hand, from the crontab (cron table) files, which contain the "schedule" or "to-do list" itself, i.e. the commands to be executed and their exact timing.
In this article, we will thoroughly explore the history of Cron, examine its structure and operation, present its syntax in detail, and discuss the differences between user and system tasks. Our goal is that by the end of the article, everyone will be confident in using this extremely useful tool to automate their own systems.
history
The history of Cron dates back to the early days of the Unix operating system, in the mid-1970s, within the walls of the legendary AT&T Bell Labs. The original concept and first implementation Ken thompson, one of the fathers of Unix, although other engineers also participated in its development. The goal was to create a simple but reliable mechanism to automate routine maintenance tasks.
The first versions were much simpler than the daemon we know today; it was essentially a program that ran every minute, read a configuration file, and started the tasks that were due. However, the vast majority of Cron versions used in modern Linux distributions are based on a later, significantly improved version, which Paul Vixie written in 1987. This is the so-called Vixie cron It now ran as a true daemon (background service) and introduced several key innovations, including support for user-level crontab files, more detailed scheduling syntax (such as specifying increments and lists), and special strings tied to system events (e.g. @reboot).
Vixie cron proved to be so successful and robust that over time it became practically an industry standard and its functionality was incorporated into POSIX This continuous development has resulted in a reliable and versatile tool that is now a cornerstone of automation for most Unix-like systems, including Linux.
Structure and operation
The Cron system is not a single program, but an ecosystem of several components that work closely together. Understanding the roles and relationships of these elements is essential for reliable operation. Below, we will examine in detail the three basic pillars of Cron: the daemon that runs in the background, the crontab files containing the instructions, and the command used to manage them.
The cron daemon
The heart and engine of the system is the cron demon (a daemon (English term referring to programs that run in the background, without user interaction). This service starts automatically when the system boots and from then on does its work silently, in the background. Its main and only task is to "wake up" every minute, check all existing crontab files and look for a task that is scheduled to run exactly at the current minute. If it finds one, it runs the specified command or script on behalf of the user specified in the crontab file, and then goes back to sleep for the next minute. On most systems, the process name is cron vagy crond.
The crontab files
A crontab (cron table) files are simple text files that contain a list of tasks you want to automate. Each line represents a separate scheduled task (cronjob) which consists of two main parts: the timing pattern (when to run) and the command to execute. The system distinguishes two main types:
- User crontab files: Each user can have their own individual crontab file. These are usually stored in a central system called spool stored in a directory (typically in
/var/spool/cron/crontabs/These files should never be accessed directly, they can only be edited using thecrontabwe need to use the command. - System-wide crontab files: These are managed by the system administrator (root) and contain tasks that apply to the entire system. The central file is
/etc/crontab, but there are also special libraries (e.g./etc/cron.d/,/etc/cron.daily/). We will discuss these in detail in a later chapter.
The crontab command
As mentioned above, to securely manage user crontab files, crontab command. This program ensures that the syntax is not broken while editing the file, and that the cron daemon is immediately notified of the updated job list after saving the changes. Its most commonly used switches are:
crontab -l: List the contents of the current user's crontab file. This is the safest way to view existing jobs.
In the image above, for example, root we can see the listing of user crontab. In this case, the tasks are executed in a ISPConfig more web hosting control panel automatically, which are responsible for, among other things, SSL certificate renewals and other maintenance operations.
crontab -e: Opens the crontab file for editing. The system's default command line text editor (e.g. nano vagy vim) will start. After saving and exiting, the command will automatically verify the integrity of the file and load it.
Here we see the same tasks as in the listing, but now in the GNU nano opened in a text editor, ready for editing.
crontab -r: Removes the current user complete crontab file. Important: This command does not ask for confirmation, so be very careful when using it!
Syntax of crontab
In a crontab file, every line that is not empty or does not have an ellipsis (#) (i.e. not a comment), a timed task, a so-called cronjobdefines . Such a line always consists of two main parts: the first five fields are timing defines, and the following part is the command to executeTo use crontab correctly, it is essential to have a precise understanding of this structure.
The general format is as follows:
perc óra nap hónap hét_napja /elérési/út/a/parancshoz --kapcsolók
Timing fields
The five timing fields, separated by spaces, specify the exact time the command will run. The fields have the following meanings, in strict order:
- 1. Minute: Value
0and59can be between. - 2. Hour: Value
0and23(in 24-hour format). - 3. Day of month: Value
1and31can be between. - 4. Month: Value
1and12(or English, three-letter abbreviations:jan, feb, mar, ...). - 5. Day of week: Value
0and7between where the0and the7also denotes Sunday (or in English abbreviations:sun, mon, tue, ...).
Let's look at a specific example. Let's say we want to run a backup script every day at 2:30 AM:
# Perc Óra Nap Hónap Hét_napja Parancs 30 2 * * * /usr/local/bin/backup.sh
In this example, 30 the minute, the 2 the clock. The star (*) characters mean that the task will run every day, every month, and every day of the week if the time is 2:30.
Special characters
In timing fields, we can use not only specific numbers, but also special characters, which allow us to create much more flexible rules:
- The star (
*): A "wildcard" character. It means that it matches all possible values of the given field. For example, in the hour field,*meaning: "every hour". - The comma (
,): It can be used to specify a list of values. For example, in the minute field,0,15,30,45meaning: "at the 0th, 15th, 30th and 45th minutes". - The hyphen (
-): Defines a range of values. For example, in the day of the week field,1-5means "Monday to Friday" (not on weekends). - The slash (
/): Specifies an interval. This is usually used in combination with an asterisk or a range. For example, in the minutes field,*/15means "every 15 minutes" (i.e. at 0, 15, 30 and 45). In the hour field,8-18/2would mean: "every other hour between 8 a.m. and 6 p.m."
Special timing strings
Modern Cron implementations also support some user-friendly special strings that can be used to specify the most common timings in a much more readable way. These are equivalent to their numeric counterparts.
Tip: Timing made easier
Instead of having to memorize the exact meaning of the asterisks for common cases, we can use the following, much more descriptive aliases:
@reboot: It runs once at system startup.@yearlyvagy@annually: It runs once a year, which is equivalent to this:0 0 1 1 *(January 1st of each year at midnight).@monthly: It runs once a month, which is equivalent to this:0 0 1 * *(at midnight on the first day of every month).@weekly: It runs once a week, which is equivalent to this:0 0 * * 0(every Sunday at midnight).@dailyvagy@midnight: It runs once a day, which is equivalent to this:0 0 * * *(every day at midnight).@hourly: It runs hourly, which is equivalent to this:0 * * * *(at the 0th minute of every hour).
For example, we can define a task that runs automatically when the system restarts like this:
@reboot /usr/local/bin/startup_check.sh
Using these strings is not only more convenient, but it also significantly improves the readability of the crontab file.
User and system-level cron jobs
Linux, as a multi-user operating system, distinguishes between tasks run by individual users and those important to the system as a whole. This separation also applies to Cron. Basically, we can define scheduled tasks at two levels: at the user level, in our own crontab file, and at the system level, in the /etc using configuration files located in the directory.
User crontab
As we mentioned earlier, each user on the system can create their own crontab file. This is the most common and easiest way to create scheduled tasks if they are tied to your own user account.
- Treatment: Only the
crontab -e(edit) andcrontab -l(listing) commands. - Privileges: The tasks defined here will always run with the privileges of the given user. For example, commands in the crontab of the user named 'jani' will be executed under the account name 'jani'.
- Location: The system is
/var/spool/cron/crontabs/stores these files in the directory, the file name is the same as the username. This directory and the files in it should never be edited directly!
System-wide crontab
System-wide cron jobs are machine-wide tasks, typically for maintenance, logging, or system checks. They can only be run by the root can be managed by the user and defined in several ways.
The /etc/crontab file
This is the central, system-wide crontab file. Although its syntax is very similar to a user crontab, there is one key difference: the timing fields and the command a username is requiredThis determines on whose behalf the cron daemon should run the given command.
So the format changes to:
perc óra nap hónap hét_napja felhasználó parancs
The picture above shows a typical /etc/crontab we see the contents of the file. It is clearly visible that before the commands (e.g. run-parts) is listed there root username. This file is responsible, among other things, for the system to run scripts placed in special directories hourly, daily, weekly, and monthly.
Important: A /etc/crontab file and the /etc/cron.d/ Files in the directory must be edited directly with a text editor (e.g. nano), not in the crontab with the command.
The /etc/cron.d/ directory
This library offers a much more flexible and organized way to handle system-wide tasks. Instead of having to do all the work in a central /etc/crontab we would cram it into a file, where each application or service (e.g. logrotate, sysstat) can have their own separate configuration files. The cron daemon also reads these files. Their syntax is exactly the same as /etc/crontab file, so it is also mandatory to specify the username before the command. This modularity greatly facilitates system administration and package management.
Hourly, daily, weekly and monthly libraries
The easiest way to run system-wide scripts is to use the following libraries:
/etc/cron.hourly//etc/cron.daily//etc/cron.weekly//etc/cron.monthly/
The operation of these libraries is extremely simple: any executable We place a script in them, and cron will automatically execute it at intervals corresponding to the directory name (hourly, daily, etc.). No timing syntax is needed here, just the script file. The exact execution time is usually specified in /etc/crontab file defines, the run-parts command.
Environment variables and output management
A common problem is that a command or script works perfectly when run from the command line, but when run from a scheduled crontab, it gives an error or doesn't start at all. The reason for this is almost always that the execution environment provided by cron is significantly different from the user's interactive environment. shell Below we will review the most common pitfalls and the correct methods for dealing with them.
The PATH problem
The most common source of error is PATH environmental variable deficiency. The PATH determines which directories the system should search for executable programs. When you log in to a terminal, the system is presented with a very large PATHsets (e.g. /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin), so most commands can simply be called by their name. In contrast, cron is an extremely minimalist, strictly limited command for security reasons. PATHuses (typically only /usr/bin:/bin). Therefore, if a cron job tries to start a program that is outside of these directories (e.g. the /usr/local/binin), you won't find it.
Error: Command not found
The "command not found" error message is almost a sure sign of PATH There are two reliable solutions to avoid this phenomenon:
- Using absolute paths: This is the safest and most recommended method. Instead of
sajat_script.sh, always specify the full path to the command, for example/opt/scripts/sajat_script.shThe exact location of the commands is in thewhich parancs_nevewe can query it with a command. - Setting PATH in crontab: If you use a lot of commands, it may be more convenient to explicitly set the desired time at the beginning of the crontab file.
PATHSimply insert a line before the tasks:PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Redirect output
By default, cron attempts to email the standard output (STDOUT) and standard error (STDERR) of each job it runs to the user whose crontab the job is in. This can be useful for debugging, but continuous emails from successfully running jobs quickly become unnecessary noise.
If we don't need the output, we can redirect it to "nothing", the /dev/null special device. The most commonly used formula:
* * * * * /eleresi/ut/parancs >/dev/null 2>&1
This line reads the standard output (>) to /dev/nullredirects to , then the error output (2>) also sends it to the same place where standard output points (&1). If we want to log the operation of a task, we can also direct the output to a file:
* * * * * /eleresi/ut/parancs >> /var/log/sajat_script.log 2>&1
Here is the >> The operator appends the output to the end of the file, so a log of each run is maintained.
The MAILTO variable
A more elegant way to handle outputs via email is MAILTO Using a variable within the crontab file. This allows us to globally control the delivery of notifications.
- If you want to receive all job output to a specific email address (instead of local delivery), specify the address at the beginning of the file:
MAILTO="rendszergazda@weboldalunk.hu" - If you don't want to receive any emails at all (and don't want to write the redirect at the end of every line), set the variable to an empty value:
Tip: Block emails completely
The easiest way to globally disable all email notifications is to add the following line to the very beginning of our crontab file:
MAILTO=""
This will prevent cron from sending emails about the output of any job. This setting makes the crontab file much cleaner than having to manually redirect the output at the end of each line.
Anacron: A helper for desktops and laptops
The classic cron daemon works perfectly on servers that run 24/7. But what about machines—like desktop workstations or laptops—that you regularly turn off or put into sleep mode? If a daily maintenance task is scheduled for 3 a.m. but your machine is currently turned off, cron simply won't be able to run it, and the task will be skipped.
This is exactly the solution to this problem: Anacron (from the phrase "anachronistic cron"). Anacron is not a replacement for the cron daemon, but a clever addition to it. It does not run as a daemon in the background, but is started by cron at regular intervals (typically hourly or daily). When it starts, Anacron checks its own timestamp files to see if any daily, weekly, or monthly tasks have been run in the past period (e.g., the last 1, 7, or 30 days).
If it detects that a task has been missed due to the machine being off, it will start it after a set delay. This ensures that important maintenance scripts (e.g. /etc/cron.daily, /etc/cron.weekly in libraries) will definitely be executed sooner or later, even if the machine is not running continuously.
Operation in practice
Most modern desktop Linux distributions (like Debian, Ubuntu, Fedora) use Anacron by default to run tasks at regular intervals (daily, weekly, monthly). We can see this from the fact that /etc/crontab in the run-parts commands are often preceded by a test that checks for the existence of anacron. The Anacron configuration file is typically /etc/anacrontab, in which the frequency of tasks (in days) and the delay before running (in minutes) are specified.
In summary, while the cron for precise, minute-by-minute timings (e.g. "every day at 14:05 PM"), while anachron It ensures guaranteed, periodic execution of tasks on systems that are not continuously operational.
- 36 views


