When we build software and define server requirements for the administrator, one item very often on the list is "cron required". A quick aside: some will say that listing it separately is pointless, because cron is a classic part of every server. Maybe so, but:
- we remember cases at our company where the administrator did not set up cron because they "decided it was not needed",
- even when it was there, we did not always have access to it.
It is true that cron is one of the basic components of a server, but above all it is an extremely useful tool in most web applications. That is why using it feels as natural as adding another API endpoint or another feature to a client app. At least that is how it seems. Programmers, especially experienced ones, know the name "cron" so well that it has become a synonym for all similar mechanisms, whatever they are called in a given environment or technology. But we have to remember that very young IT adepts or clients may not understand this slang. And even if they do, using cron is not always obvious: some asterisks, some numbers, and nothing works the way it should...
That is why this article explains what cron is, when it is used and how to use it. The text is aimed mostly at beginners, but we think that a few of the application-related tips may also be useful, or inspiring, for more advanced readers.
What is cron?
Put simply, cron is a program that runs scheduled tasks at regular intervals. It is a typical Linux tool, or more precisely a Unix tool: it was created in May 1975 at AT&T Bell Laboratories (like UNIX itself), which is now called Nokia Bell Labs. And yes, the "Bell" is no coincidence, since the foundations of this distinguished institution were laid by the well-known Alexander Graham Bell at the end of the 19th century. The name of the program comes from the Greek word chronos, meaning time. But back to the point.
Imagine a situation where a system has to perform certain tasks without our involvement. One example is generating a report every night and sending it to users. Having a person sit at the computer at the same hour every day and click a button is pointless and tiring. It is better to rely on a computer system that runs all the time and does it for us at the right moment. That is what cron is for: we can use it to define when (or how often) it should run certain actions. Technically, it is a service (called a daemon in Linux) that works in the background and keeps checking its list of jobs to see whether it should run any of them right now.
Cron was in fact the first program of this kind and it has several implementations, of which fcron, for example, is popular. In practice, though, when someone says they want or need cron, everybody knows what is meant, and it is rarely necessary to decide which implementation to install. It is worth distinguishing the term "cron" from "crontab", though. The latter is the program, or the tables of the cron program, from which job definitions are read. We can think of crontabs as lists of actions written by different people who have access to the server. That is why jobs are defined with the crontab command: each system user has their own list, which the cron service then collects and runs with that user's permissions.
How do you define jobs?
From the previous section we learned that to define cron jobs we should use the crontab command, specifically crontab -e, which lets us edit the entries. This happens in a text editor, so the first time you run this command the system may ask which program you want to use. It is purely a matter of convenience and habit: the undersigned always picks Vim, though most people stick with simple nano.
The table consists of entries that must follow this structure:
m h dom mon dow command
As you can see, each job has six columns. The first five define the time or frequency of execution, and the last one is the actual command. This is where the magic happens, in those strange-looking lines with asterisks. It is fairly simple to understand, though.
The first five columns are interpreted as follows:
m- minute, range 0 to 59h- hour, range 0 to 23dom- day of the month, range 1 to 31mon- month, range 1 to 12dow- day of the week, range 0 to 7, where Sunday is both 0 and 7, Monday is 1, and so on
Usually we do not want to fill in every column with a specific value, so we will very often use special characters. Cron lets you use:
- an asterisk (
*), which means every value, e.g. "every minute". - a hyphen (
-), which means a range of values, e.g.1-3is "when the value is from 1 to 3". - a slash (
/), which sets the frequency, e.g.*/2is "every second value". There does not have to be an asterisk before the slash, and you can narrow the range further: writing6-16/2means "from 6 to 16, but every two units (that is 6, 8, 10, 12, 14, 16)". - a comma (
,), which lets you list specific values when you do not want to or cannot use a range. For example,2,5means "at value 2 or 5".
It is quite a powerful tool, but we remember well that at the beginning you may have doubts about how to define times in practice. You can picture it like this: every minute the system checks whether the current time matches any definition, and if it does, it runs that job. To understand it better, let us look at a few examples (rather artificial, but interesting):
0 10 * * * php ~/script.php - at exactly 10:00 (m = 0, h = 10) every day (dom, mon, dow = *), run the script.php script located in the user's home directory. While we are at it, note that the ~ (tilde) refers to the user who defined the job, that is, the user whose crontab contains this entry. To avoid mistakes, it is best to use absolute paths.
*/30 6 * * 1,5 cp ~/file1.txt ~/copy.txt - on Mondays and Fridays (1 and 5), when the clock strikes six (6), copy file1.txt to copy.txt every half hour (*/30). In practice, during one week this operation will run four times: on Monday at 6:00 and 6:30, and on Friday at the same times. Only these moments match the given time definition.
22 * * * * mysqldump -u user -d db > ~/"backup_$(date +\%Y-\%m-\%d_\%H-\%M-\%S).sql" - every hour at minute 22 (so 14:22, 15:22, 16:22 and so on), every day, make a backup of the MySQL database to the given file. Here you can see that a command can use variables and built-in commands, such as the date, to name the resulting file. You just have to remember to format the data correctly. It is worth reading this thread and getting to know the date command.
0 20 1 3 * php ~/report.php - on exactly March 1 at 20:00 every year (regardless of the day of the week), run the script that generates the report.
As you can see, the instructions can sometimes be tricky, but mastering them is a matter of practice. And don't worry: if you are still a bit lost, you are not alone. For people new to cron, there are various interfaces that help you click together the times you want, as well as a generator with examples at crontab.guru/.
Finally, if you no longer want to run a job but would rather not delete it, remember that editing a crontab means working on a text file, so you can comment out the line by putting a hash (#) at the beginning.
Types of cron access
It is also worth noting that, depending on the hosting provider and the type of server, access to defining cron jobs can differ. The administrator will not always provide the crontab command. Sometimes it is a web interface where you choose options from a list, and sometimes there are guidelines about placing text files with strictly defined names in specific locations. If in doubt, check the provider's help system or contact them.
If we have console access and higher-than-usual permissions, it is good to know that the logs of cron runs are available in /var/log/cron or /var/log/syslog, depending on the Linux distribution and configuration. There we can check whether a given job was actually run at the scheduled time.
In this article we will not discuss configuration in detail. It is usually not relevant for programmers and is handled by administrators. Of course, that is no excuse, and it is good to know as much as possible, but you should be aware that configuring cron (as a program, not individual jobs) goes well beyond building applications. It is the domain of the people who manage the server and its operating system. Still, it is worth reading the article by Mateusz Mazurek and the one by Zaira Hira, which describe a bit more.
To close this section, let us return for a moment to defining jobs. It usually means putting a dozen or so separate commands in the crontab. That is not the only way, though, and despite its simplicity it can even be a bit misleading. If the application under development has many actions that will run periodically, you have to remember to update the crontab at every deployment, or automate that. Passing this information between the developers and the person deploying is a problem too. Some frameworks take a slightly different approach. For example, Laravel requires you to add just one command to the system table (run every minute), and the application itself manages when each of the jobs programmed into it should run. The advantage of this solution is that the developer does not have to worry about updating cron, and the code already holds the information about how often each operation runs (and you can follow the changes in the repository).
It is also worth realizing that you do not have to edit the crontab file by hand to add a new operation or change an existing one. You can keep the rules in another text file and import it with the crontab file.txt command. That can help automate this process during deployments. Just as easily, you can back up the current rules with crontab -l > backup.txt.
What can you use cron for?
Surely, while reading this part of the article, every reader has come up with many ideas about where cron could be used. They apply to both applications and various system operations. For completeness, let us list the most common uses of a scheduler for recurring tasks. And these are from real life, not theoretical considerations.
- creating tasks based on dates (e.g. "your contract ends today"),
- generating periodic reports,
- sending scheduled notifications,
- setting the statuses of objects in the system,
- deleting unused files,
- recalculating aggregated data,
- preparing backups of a database or files,
- fetching data from an external API (e.g. exchange rates),
- renewing an SSL certificate,
- updating files (e.g. a sitemap or an RSS feed),
- clearing the cache.
There are plenty of possibilities, and this is only a handful. Almost every application has a few functions that run not on a user's request but automatically, making it easier, for example, to monitor deadlines or objects that need attention. It is hard to imagine how a newsletter would work without cron. The fact that recipients get new messages, say, every Monday at 9 a.m. is not only the result of the sender's regularity, but of exactly such "schedulers" as this unassuming Unix tool.
How do you run jobs every second?
The more observant readers have noticed that the smallest time unit in cron is a minute: the line * * * * * means running a command every 60 seconds. So how do you do it more often, even every second? First, it should be said that if the application really requires this, it is worth rethinking. Remember that jobs running in the background still put load on the system, and knowing when an operation starts does not mean we know when it ends. With bigger tasks it may turn out that a job started on schedule at, say, 6:12 only finishes at 6:20. Of course, most jobs on a server finish within a second, but in more complex systems it can be several seconds. If you run such a job every second, the system will be more and more loaded, which can end badly. In most cases running every minute is more than enough, and even that, used carelessly, can exceed resource limits.
That does not mean there is no way to "trick" cron into running a job at a specific second. It is not very hard either, as long as we know the sleep operation, which exists in Linux and in practically every programming language and lets an application "fall asleep" for a given number of seconds. The key is to start the job at second 0 and wait a moment for the time we are interested in. In some cases this can be done in the crontab itself with a system command, and if the application's technology allows it, it can also be done in the application.
I don't have cron. What now?
Today, not being able to use cron is quite rare, but from our experience it can happen, especially with very cheap or small hosting plans. Sometimes it is also a matter of permissions, although that should not be an excuse, since every user has their own crontab and correspondingly limited capabilities.
Let us assume, though, that this situation has really hit us. What can we do besides running commands by hand? There are at least two options. The first is to perform certain actions when a user logs in for the first time on a given day, in the background where possible. This applies especially to recalculating aggregated data, e.g. for the dashboard of a company logging into the system. The big drawback is that the operation is time-consuming and that someone has to log in, which may or may not happen. The second solution, much better, is to expose an API service and call it every day from an external source that is itself driven by cron. It imitates periodic execution of operations, but it requires public access to the service and writing yet another service. Still, it is an option when the standard route is not available.
It is also worth mentioning that sometimes cron may not work simply because... nobody started or installed it. In that case, if you have the right permissions, check the daemon's status with sudo service cron status or another command suitable for your Linux distribution. Various options and ways of starting it are described in this guide.
Cron in different environments
When talking about cron, we have been staying within Linux the whole time. That is not surprising, because this operating system rules most servers. Since the tool was created in the days of UNIX, you can expect to find it in macOS as well, and indeed it is there and you can use it.
And what about Windows? There we have no simple access to cron, but we have two ways to deal with it. There is the Windows Subsystem for Linux (WSL), which lets you run Linux inside Windows. Depending on the distribution, the program may already be there but switched off (as is the case with Debian), but this is easy to change using the tips from the previous section. Starting the scheduler service automatically is not as simple as it might seem, but it is possible too.
On the other hand, remember that Windows itself offers a replacement in the form of Task Scheduler, available from the Start menu or as Taskschd (case matters) from the command line. This program lets you create tasks through a graphical interface, although there is also an option to manage them from the console, which is worth a look (it has long been known that programmers get along better with a console interface than with a GUI).
Summary
Recurring tasks appear in practically every application built by a software house, and with cron you simply have to learn to live and work. Especially since it is not a complicated tool, yet it offers great possibilities, also in situations where you would not expect it (e.g. recalculating helper values in the background). We encourage you to try it yourself, because only practice lets you master this kind of technique properly.
Best regards and thank you - Jakub Rojek.


