Creating More Advanced Cron Jobs
Now that you understand the basics, let's create a more advanced cron job that logs system information.
Let's create a cron job that will log information about the system's memory usage every hour. This type of monitoring can be useful for tracking system performance over time.
First, let's create a shell script that will collect the memory information:
nano ~/project/memory_check.sh
In the nano editor, add the following content:
#!/bin/bash
echo "Memory check at $(date)" >> ~/project/memory_log.txt
free -m >> ~/project/memory_log.txt
echo "--------------------" >> ~/project/memory_log.txt
This script will:
- Add a timestamp to the log
- Run the
free -m
command to display memory usage in megabytes
- Add a separator line for readability
Save and exit the editor (press Ctrl+O
, Enter
, then Ctrl+X
).
Now, make the script executable:
chmod +x ~/project/memory_check.sh
You can test the script to ensure it works correctly:
~/project/memory_check.sh
Check the output file:
cat ~/project/memory_log.txt
You should see output that includes the timestamp, memory usage information, and a separator line.
Now, let's schedule this script to run hourly using crontab:
crontab -e
Add the following line (while keeping your existing cron job):
0 * * * * ~/project/memory_check.sh
This will run the memory check script at the beginning of every hour. Save and exit the editor.
To verify the new cron job has been added:
crontab -l
You should see both cron jobs:
*/5 * * * * date >> ~/project/date_log.txt
0 * * * * ~/project/memory_check.sh
Using Special Time Strings
Cron also supports some special time strings for common scheduling patterns:
@hourly
- Same as 0 * * * *
@daily
- Same as 0 0 * * *
@weekly
- Same as 0 0 * * 0
@monthly
- Same as 0 0 1 * *
@reboot
- Run at system startup
Let's add a job that runs daily using these special strings:
crontab -e
Add the following line:
@daily echo "Daily check on $(date)" >> ~/project/daily_check.txt
Save and exit the editor. This will create a new entry in the daily_check.txt
file once per day at midnight.
To verify the new cron job has been added:
crontab -l
You should now see all three cron jobs:
*/5 * * * * date >> ~/project/date_log.txt
0 * * * * ~/project/memory_check.sh
@daily echo "Daily check on $(date)" >> ~/project/daily_check.txt
Managing Cron Job Output
By default, cron sends any output from jobs to the user's email. If you want to discard the output completely, you can redirect it to /dev/null
:
*/10 * * * * ~/project/some_script.sh > /dev/null 2>&1
This is a common practice for scripts that produce output you don't need to keep.