Do you need to get up at 2 a.m., clear the logs, clear short-term recordsdata, and run the identical server upkeep duties each single day?
Effectively, me neither. Nor do the thousands and thousands of server admins who handle the 14+ billion servers internationally.
So, cease the insanity — I urge you!
Cron jobs are constructed for that.
As a result of, genuinely, nothing says “competent sysadmin” like being quick asleep and taking credit score for the work your scripts deal with for you. It’s known as “using your assets.”
With cron jobs:
- Your boss thinks you’re devoted.
- Your server is aware of you’re lazy.
- You’ve got this stunning symbiotic relationship known as automation.
In the present day, you’re going to change into a cron jobs professional.
First, What’s a Cron Job? (The Not-Boring Model)
A cron job is actually a job scheduler constructed into Unix-like working techniques (Linux, macOS) that permits you to run Linux instructions robotically at specified instances and dates.
Consider it like a to-do listing to your server, however…this one really will get accomplished.
Cron in Metaphors
In case your server infrastructure had been a restaurant:
- The cron daemon is the supervisor checking the every day schedule.
- The crontab is the workers task board.
- Every cron job is a job assigned to a particular workers member at a particular time.
- The command is the precise work being carried out.
When the clock hits the scheduled time, the supervisor faucets the assigned worker on the shoulder and says, “It’s showtime!”
The worker then executes their job with out query or grievance.
If solely we people had been this dependable, the world could be a special place!
The Anatomy of a Cron Job
Each cron job consists of two primary components:
- When to run (the schedule)
- What to run (the command or script to execute)
The schedule makes use of a particular syntax that may seem like some laptop wizardry at first look:
However take a more in-depth look and it’ll begin to make sense.
Every asterisk might be changed with particular values, ranges, or intervals to create exactly the schedule you want.
Why Server Admins Love Cron Jobs
There’s a motive why server admins (even me) get misty-eyed when discussing cron jobs.
They flip server administration into one thing that (no less than remotely) resembles work-life stability.
1. They Save You Time
Keep in mind time? That factor you by no means have sufficient of? Cron jobs give it again. You set them, you neglect them, and also you’re just about by no means taking a look at them.
(Effectively, till they break or it’s essential to change the schedule.)
2. They Preserve Consistency
People are inconsistent. We neglect issues. We make typos. We get distracted by cat movies. Cron jobs carry out the precise job, the very same means, each single time — no exceptions.
3. Your Server By no means Sleeps
With cron jobs, important upkeep occurs 24/7/365, whether or not you’re awake, asleep, or on a seaside sipping margaritas.
4. Error Logs > Human Reminiscence
If you manually carry out duties, are you able to keep in mind precisely what you probably did and precisely whenever you did it? In all probability not.
However cron jobs might be configured to log their exercise, making a paper path of all automated actions for troubleshooting and verification.
5. They’re Constructed for Scalability
As your infrastructure grows, manually managing the whole lot turns into exponentially harder. Cron jobs scale effortlessly.
That means, the identical job can run throughout a number of servers with out requiring further time from you.
Setting Up Cron Jobs: A Step-by-Step Information
Sufficient principle! It’s essential to get your arms soiled with some sensible cron job setup.
Step 1: Affirm Cron Is Put in
Most Unix-like techniques have cron pre-installed. To verify if it’s accessible to be used, sort the beneath command:
crontab -e
Relying on the default editor, the command will open the crontab in your particular editor. You probably have by no means used crontab earlier than, it’d ask you to set the default editor.

If the terminal responds with command not discovered, you’ll want to put in cron with the beneath instructions:
- On Ubuntu/Debian:
sudo apt replace && sudo apt set up cron
- On CentOS/RHEL:
sudo yum set up cronie
As soon as carried out, begin and allow the cron service:
sudo systemctl begin cron
sudo systemctl allow cron
With the begin and allow instructions, we’re beginning the cron service to execute the cron jobs.
And with allow, we guarantee that even when your server restarts, the cron service robotically restarts with it, and no cron jobs are missed.
Nerd Notice: CentOS calls the cron service “crond”, so you’ll need to begin and allow the crond service.
Step 2: Understanding the Crontab
Alright, open the crontab or the crontable to start including your scheduled jobs.
Every consumer on the system can have their very own crontab file. Moreover, there’s a system-wide crontab.
To edit your private crontab:
crontab -e
This opens your crontab file in your default textual content editor. If that is your first time, select the nano editor (possibility 1) because it’s essentially the most beginner-friendly.
For system-wide crontabs, run the beneath command with sudo privileges:
sudo nano /and many others/crontab

Step 3: Cron Job Syntax
We’ve already talked in regards to the primary construction within the anatomy of cron jobs earlier than.
However making a cron job might be complicated generally. Crontab.guru helps you visualize the job schedules as you sort them.

Now for the enjoyable half — writing our first cron job. Let’s check out some widespread cron job schedules:
Each minute:
* * * * /path/to/command
Each hour at minute 0:
0 * * * * /path/to/command
Day-after-day at midnight:
0 0 * * * /path/to/command
Each Monday at 3 a.m.:
0 3 * * 1 /path/to/command
Each quarter-hour:
*/15 * * * * /path/to/command
First day of each month at 6:30 a.m.:
30 6 1 * * /path/to/command
Step 4: Creating Your First Cron Job
Let’s transfer to making a easy backup cron job to your server.
The duty beneath creates a backup of your web site each day at 2 a.m.
0 2 * * * tar -czf /path/to/backup/website-backup-$(date +%Ypercentmpercentd).tar.gz /path/to/your/web site
It can output a compressed tar archive of your web site listing with the present date because the filename.
Step 5: Save and Confirm
Now, exit the editor. In nano, press Ctrl+X after which hit Y.
To view your present crontab and confirm your job was added:
crontab -l

That’s it! Your first cron job is now arrange and can run robotically on the scheduled time.
Sensible Cron Job Examples for Web site Managers
Now that you realize the fundamentals, let’s discover some sensible cron jobs that may make your life as a web site supervisor considerably simpler.
Database Backups
MySQL database backup (every day at 1 a.m.):
0 1 * * * mysqldump -u username -p'password' database_name | gzip > /path/to/backups/db-backup-$(date +%Ypercentmpercentd).sql.gz
Log Rotation and Cleanup
Clear logs older than 7 days (weekly on Sundays):
0 0 * * 0 discover /path/to/logs -type f -name "*.log" -mtime +7 -delete
Web site Efficiency Monitoring
Verify web site response time each 5 minutes:
*/5 * * * * curl -o /dev/null -s -w "%{http_code} %{time_total}sn" instance.com >> /path/to/logs/website-performance.log
Content material Updates
Fetch and replace dynamic content material (each hour):
0 * * * * /path/to/content-update-script.sh
E-mail Reviews
Ship a weekly site visitors abstract each Monday at 9 a.m.:
0 9 * * 1 /path/to/generate-and-email-report.sh
Safety Scans
Run a safety scan script each night time at 3 a.m.:
0 3 * * * /path/to/security-scan.sh
Cron Job Finest Practices: Dos and Don’ts
To verify your cron jobs run easily and don’t trigger extra issues than they remedy, listed here are some vital finest practices.
The Dos
- At all times use full paths to instructions and recordsdata: Your cron atmosphere doesn’t have the identical PATH as your consumer shell, so
“/usr/bin/python”
is healthier than simply python. - Redirect output to forestall e-mail spamming: By default, cron emails any output to the consumer. Add
>/dev/null 2>&1
to suppress output or redirect to a log file as a substitute. - Check your instructions earlier than scheduling them: Run your command manually to make sure it really works as anticipated.
Add feedback to elucidate every job — Future you’ll thank current you for documenting what every cron job does and why.
Each day database backup - Added by Jane on 2023-05-15
0 1 * * * /path/to/backup-script.sh
Think about using lockfiles for long-running jobs to forestall a brand new occasion from beginning if the earlier one continues to be working.
0 * * * * flock -n /tmp/script.lock /path/to/your/script.sh
The Don’ts
- Don’t schedule resource-intensive jobs throughout peak hours: Your backup doesn’t must run at midday when your web site is busiest.
- Don’t use relative paths:
“./script.sh”
will virtually definitely fail in cron. - Don’t neglect atmosphere variables: Cron doesn’t load your .bashrc or .profile. Set any required variables within the crontab or script.
- Don’t overlook logging: With out correct logging, debugging cron jobs could be a nightmare.
- Don’t overdo it: Too many frequent cron jobs can overload your server. Be strategic.
What To Do When Cron Jobs Go Incorrect
The one time you need to look again at a cron job is when it breaks — and when it breaks, right here’s how one can diagnose and repair widespread points.
Widespread Drawback #1: Job Doesn’t Run
Signs: Your scheduled job doesn’t appear to be executing in any respect.
Potential fixes:
- Verify cron daemon is working: The “systemctl” standing cron
- Confirm your crontab syntax: Use a device like crontab.guru
- Guarantee full paths to executables: Which command to search out full paths
- Verify file permissions: Scripts should be executable (chmod +x script.sh)
Widespread Drawback #2: Job Runs However Fails
Signs: The job executes however doesn’t full its job efficiently.
Potential fixes:
- Redirect output to a log file to see errors:
* * * * /path/to/script.sh > /path/to/script.log 2>&1
- Check the command manually with the identical atmosphere
- Verify for dependencies that may be lacking within the cron atmosphere
Widespread Drawback #3: E-mail Flooding
Signs: Your inbox is flooded with cron output emails.
Potential fixes:
- Redirect output to null:
>/dev/null 2>&1
- Redirect to a log file:
>/path/to/logfile.log 2>&1
Solely e-mail on errors:
* * * * /path/to/script.sh >/dev/null || echo "Script failed" | mail -s "Cron failure" you@instance.com
Widespread Drawback #4: Timing Points
Signs: Jobs run at sudden instances or frequencies.
Potential fixes:
- Double-check your timezone settings — date vs. cron’s expectation
- Concentrate on DST modifications that may have an effect on timing
- Use specific time frames as a substitute of relative ones when precision issues
Superior Cron Job Writing Methods
We’ve regarded on the fundamentals, and you’re just about a professional with cron jobs by now. However this part will take you a step additional.
Utilizing Particular Strings
You don’t at all times want to jot down cron jobs with these asterisk indicators. There are some particular strings that allow you to arrange cron jobs fairly simply.
- @yearly or @yearly: Run annually (0 0 1 1 *)
- @month-to-month: Run as soon as a month (0 0 1 * *)
- @weekly: Run as soon as per week (0 0 * * 0)
- @every day or @midnight: Run as soon as a day (0 0 * * *)
- @hourly: Run as soon as an hour (0 * * * *)
- @reboot: Run as soon as at startup
For instance, if you would like one thing to run every day, simply write the beneath command:
@every day /path/to/daily-backup.sh
Atmosphere Variables in Crontab
To keep away from repeating a string again and again in your cron jobs (for instance, a particular path, or your admin e-mail), arrange atmosphere variables initially of your crontab.
You possibly can then reuse the variables as required inside your scripts or instructions.
SHELL=/bin/bash
PATH=/usr/native/sbin:/usr/native/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=admin@instance.com
# This job will ship errors to admin@instance.com
0 2 * * * /path/to/mailing_script.sh
If we use the atmosphere variable MAILTO in our mailing_script.sh, the script will robotically ship an e-mail to the right e-mail handle.
With this, altering the admin e-mail will solely require altering the worth of the MAILTO variable, as a substitute of creating modifications throughout all scripts.
Working Jobs As Totally different Customers
You probably have superuser entry, you possibly can edit one other consumer’s crontab:
sudo crontab -u username -e
Utilizing Anacron for Machines That Aren’t At all times On
In contrast to cron, anacron ensures jobs run even when the pc was off through the scheduled time:
sudo apt set up anacron
Edit /and many others/anacrontab so as to add jobs that may run when the system comes again on-line.
Job Chaining for Advanced Workflows
Run jobs in sequence:
0 1 * * * /path/to/first-script.sh && /path/to/second-script.sh
Monitoring Cron Jobs
For severe server administration, think about instruments like Cronitor that present monitoring and alerts to your cron jobs.
0 * * * * cronitor exec check-12345 -- /path/to/your/script.sh
Let’s Discuss Prices
Cron jobs can’t exist in isolation. They want a server and a service working on a server that it’s essential to handle.
Now, when you’re studying this text, it’s extremely doubtless that you’ve got a server to your web site or utility.
In reality, when you’re internet hosting with DreamHost VPS or any Linux-based internet hosting supplier, you’ve already received the whole lot it’s essential to get began with automating your server administration duties.
If not, a $10/month VPS is all you’d want, particularly when beginning out.
For these already working a DreamHost VPS, the method couldn’t be extra simple:
- SSH into your server
- Run crontab -e to edit your private cron desk
- Add your scheduled duties
- Save, and let the automation start!
SSH
Safe Shell Protocol (SSH) is a cryptographic community protocol for working companies securely by an unsecured community. It’s largely used for command-line executions and distant logins.
That’s it. The infrastructure you’re already paying for all of a sudden turns into extra priceless, extra environment friendly.
Your Server’s New Autopilot
Congratulations!
You’ve graduated from guide labor to automation wizardry. With cron jobs dealing with the routine upkeep, backups, and monitoring, you possibly can give attention to rising your web site and enterprise somewhat than babysitting the server.
And keep in mind, it’s going to be a course of. The automation will change into extra subtle as you add increasingly more duties to it.
However for now, begin with just a few important cron jobs, monitor how they carry out, and progressively broaden your automation as you develop extra comfy with the method.
Now go on and take that nap, since you simply saved your self a buttload of time.
Did you take pleasure in this text?