Automated tasks in Linux are called cron jobs, and they run on a schedule you define to handle repetitive operations. If you’ve ever needed to run a script every night at midnight or clean up logs every hour, cron is your go-to tool. It’s built into almost every Linux distribution, making it a reliable way to automate routine work. This article explains everything you need to know about cron jobs, from basic setup to advanced scheduling.
Think of cron as your personal assistant for the command line. Instead of manually running commands, you tell cron when to run them, and it handles the rest. It’s been around for decades, so it’s stable and well-documented. Whether you’re a sysadmin or a hobbyist, understanding cron saves you time and reduces errors.
What Are Automated Tasks Called In Linux
In Linux, automated tasks are called cron jobs. The name comes from the cron daemon, a background process that checks a schedule file every minute. When the current time matches a scheduled time, cron executes the associated command. This system is incredibly flexible, allowing you to run tasks as often as every minute or as rarely as once a year.
Cron jobs are defined in crontab files. Each user on a Linux system can have their own crontab, plus there’s a system-wide crontab for tasks that need root privileges. The format is simple but powerful, using five time fields followed by the command to run.
Understanding The Crontab Syntax
The crontab syntax uses five fields to specify when a job runs. These fields are: minute, hour, day of month, month, and day of week. Each field can be a number, a range, a list, or a wildcard. For example, 0 5 * * * means “run at 5:00 AM every day.”
- Minute: 0-59
- Hour: 0-23
- Day of month: 1-31
- Month: 1-12 or names like jan, feb
- Day of week: 0-7 (0 and 7 both mean Sunday) or names like sun, mon
You can also use special strings like @daily or @reboot for common schedules. These make crontab files easier to read. For instance, @daily /path/to/script.sh runs the script once every day at midnight.
How To Create And Edit Crontab Files
To edit your user’s crontab, use the command crontab -e. This opens your crontab file in the default text editor. If it’s your first time, you’ll be prompted to choose an editor. Each line in the file represents one cron job, starting with the schedule and ending with the command.
- Open your terminal.
- Type
crontab -eand press Enter. - Add a new line with your schedule and command.
- Save and exit the editor.
After saving, cron automatically loads the new schedule. There’s no need to restart anything. You can list your current cron jobs with crontab -l and remove all of them with crontab -r.
Example Crontab Entries
Here are some common examples to get you started:
0 0 * * * /home/user/backup.sh– Run backup every day at midnight.*/5 * * * * /usr/bin/check_status– Run check_status every 5 minutes.0 9 * * 1-5 /home/user/report.sh– Run report at 9 AM on weekdays.@reboot /home/user/startup.sh– Run startup script at boot.
Managing Cron Jobs For Different Users
Each user has their own crontab, but root can edit anyone’s crontab using crontab -u username -e. This is useful for system administrators who need to set up tasks for other users. However, regular users can only manage their own crontab unless given special permissions.
System-wide cron jobs are stored in directories like /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. Scripts placed in these folders run at the specified intervals. There’s also /etc/crontab and /etc/cron.d/ for more complex schedules.
Using Special Time Strings
Instead of writing five fields, you can use these shortcuts:
@reboot– Run once at system startup.@yearlyor@annually– Run once a year at midnight on January 1.@monthly– Run once a month at midnight on the first day.@weekly– Run once a week at midnight on Sunday.@dailyor@midnight– Run once a day at midnight.@hourly– Run once an hour at the beginning of the hour.
These strings make crontab files cleaner and easier to understand. They’re especially handy for beginners who might find the five-field syntax confusing.
Common Use Cases For Cron Jobs
Cron jobs are used for a wide variety of tasks. Here are some practical examples:
- System maintenance: Cleaning temporary files, updating package lists, or rotating logs.
- Backups: Automating database dumps or file backups to a remote server.
- Monitoring: Checking disk usage, CPU load, or service availability.
- Reporting: Generating daily or weekly reports and emailing them.
- Data synchronization: Syncing files between servers or cloud storage.
You can also use cron to run custom scripts that interact with APIs, send notifications, or process data. The possibilities are endless, limited only by your imagination and the commands you can run.
Handling Output And Errors
By default, cron sends any output from a job to the user’s email. If you don’t want emails, you can redirect output to a file or to /dev/null. For example:
0 5 * * * /home/user/script.sh > /home/user/log.txt 2>&1– Saves both standard output and errors to a log file.0 5 * * * /home/user/script.sh > /dev/null 2>&1– Discards all output.
Redirecting output is important because cron jobs often run in the background with no terminal. If you don’t capture errors, you might not know when something goes wrong. Always test your commands manually before adding them to crontab.
Troubleshooting Cron Jobs
Sometimes cron jobs don’t run as expected. Here are common issues and solutions:
- Wrong path: Cron uses a limited PATH. Always use full paths to commands and scripts.
- Permissions: The script must be executable. Use
chmod +x script.sh. - Environment variables: Cron doesn’t load your shell profile. Set variables inside the script.
- Logs: Check
/var/log/cronorjournalctl -u cronfor errors.
Another common mistake is forgetting that cron runs in a minimal environment. If your script depends on specific environment variables, define them at the top of the script. You can also source your profile file within the script.
Testing Your Cron Jobs
Before relying on a cron job, test it thoroughly. Run the command manually in the terminal first. Then set a test schedule that runs every minute to see if it works. For example:
* * * * * /home/user/test.sh– Runs every minute.
After confirming it works, change the schedule to your desired interval. This step saves you from discovering issues at 3 AM when a critical job fails.
Advanced Cron Features
Beyond basic scheduling, cron offers some advanced features. You can use ranges like 1-5 for weekdays, steps like */10 for every 10 units, and lists like 1,15,30 for specific values. Combining these gives you fine-grained control.
For example, 0 8-17 * * 1-5 runs every hour from 8 AM to 5 PM on weekdays. You can also use month names and day names for readability, like 0 0 1 jan * to run on January 1st.
Using Cron With Scripts
Most cron jobs execute shell scripts, but they can run any executable. You can use Python, Perl, Ruby, or compiled programs. Just make sure the interpreter is specified in the script’s shebang line. For example:
#!/usr/bin/python3at the top of a Python script.
If your script needs arguments, include them in the crontab line. For instance, 0 6 * * * /home/user/backup.sh --full runs the backup script with the --full flag.
Security Considerations
Cron jobs run with the permissions of the user who owns the crontab. Be careful with scripts that modify system files or access sensitive data. Use the principle of least privilege: only give the necessary permissions.
You can restrict who can use cron by editing /etc/cron.allow and /etc/cron.deny. These files list users who are allowed or denied access. If cron.allow exists, only users listed there can create cron jobs.
Logging And Monitoring Cron Activity
For production systems, monitor your cron jobs regularly. Set up alerts for failed jobs by checking exit codes. You can add && echo "Success" || echo "Failed" to your commands and redirect output to a monitoring system.
Some tools like cronie or anacron offer additional features. Anacron is useful for systems that aren’t always running, as it ensures missed jobs are executed when the system comes back up.
Alternatives To Cron
While cron is the standard, there are alternatives for specific needs. Systemd timers are common on modern Linux distributions. They offer more features like dependency management and better logging. However, cron remains simpler for basic scheduling.
Other options include at for one-time tasks and batch for load-based scheduling. For complex workflows, consider tools like Jenkins or Apache Airflow, but for most users, cron is sufficient.
Migrating From Cron To Systemd Timers
If you’re using systemd, you might prefer timers over cron. They use unit files and offer more control. However, cron is still widely supported and easier for beginners. Stick with cron unless you need systemd-specific features.
To create a systemd timer, you need a service file and a timer file. This is more complex than editing a crontab, but it integrates better with systemd’s logging and dependency system.
Frequently Asked Questions
What are automated tasks called in linux?
Automated tasks in Linux are called cron jobs. They are scheduled using the cron daemon and defined in crontab files.
How do I list all cron jobs for a user?
Use the command crontab -l to list your own cron jobs. Root can use crontab -u username -l to list another user’s jobs.
Can I run a cron job every second?
No, cron’s minimum interval is one minute. For sub-minute tasks, use a loop with sleep inside a script, or use a tool like systemd timers with OnCalendar= for more precision.
Why isn’t my cron job running?
Check the script’s permissions, use full paths, verify the crontab syntax, and look at system logs. Common issues include missing executables and environment variables.
How do I edit another user’s crontab?
As root, use crontab -u username -e. This requires root privileges and is useful for system administrators managing multiple users.
Best Practices For Cron Jobs
To keep your cron jobs reliable, follow these tips:
- Always use absolute paths for commands and files.
- Redirect output to logs or suppress it with
/dev/null. - Test commands manually before adding them to crontab.
- Set proper permissions on scripts (executable, owned by correct user).
- Document your cron jobs with comments in the crontab file.
Also, avoid running heavy tasks during peak hours. Schedule maintenance jobs for off-peak times to minimize impact on users. If a job fails, investigate immediately to prevent cascading issues.
Example: A Complete Backup Cron Job
Let’s walk through a real example. Suppose you want to backup a database every night at 2 AM and keep logs. First, create a script:
#!/bin/bashmysqldump -u root mydb > /backups/mydb_$(date +\%Y\%m\%d).sqlgzip /backups/mydb_$(date +\%Y\%m\%d).sql
Make it executable with chmod +x /home/user/backup_db.sh. Then add this crontab line:
0 2 * * * /home/user/backup_db.sh > /home/user/backup_log.txt 2>&1
This runs the script at 2 AM daily, saving output to a log file. The % signs in the date command need to be escaped with backslashes in crontab.
Conclusion
Now you know what automated tasks are called in linux: cron jobs. They are a simple yet powerful way to automate repetitive tasks. By mastering crontab syntax and best practices, you can save time and reduce manual errors. Start with small tasks like clearing temp files, then move to complex workflows. With cron, your Linux system works for you, even when you’re not watching.
Remember to test everything, check logs, and keep your scripts simple. Cron has been around for decades because it works. Give it a try today and see how much easier system administration becomes.