So you want to set up a Cron Job on your linux machine? If you ask Google, all you’ll get is “Open crontab -e” and add 0 0 * * 0 /path/to/your/command
But what if the job you want to run is slightly more complicated? This post is intended to be a quick guide, for the lazy (like myself) who don’t want to read the Cron Guide in its entirety.
Let’s get started!
- Create a script for the job you want to run, we’ll call it with cron:
touch /path/to/your/script.sh - Make your script executable:
sudo chmod +X /path/to/your/script.sh - Run
sudo crontab -eto edit your Cron job file. -
Set up a test job – add the following to the end of the Cron file:
* * * * * su - <user.name> -c 'cd /home/<user.name>/ && /path/to/your/script.sh' >> /tmp/script-output.log 2>&1Explanation:
* * * * *runs your job every minute, and>> /tmp/script-output.log 2>&1logs the output cronjob runs asrootby default, and will not have access to your configs and settings.su - <user.name>runs the cronjob as the user you specify. -
Cron runs in an isolated environment with very little access to the tools you’ve installed. In your
script.sh, you need to give cron the tools it needs for code execution:# Give it access to PATHs HOME="<your profile's home directory>" export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:$PATH" # Set environment variables so cron has access to tools and configs. For example: export GH_CONFIG_DIR="$HOME/.config/gh" source $HOME/.bashrc # add some information for logging purposes current_datetime=$(date +%Y-%m-%dT%H:%M:%S) echo "current time is {$current_datetime}" # You can call a complicated set of commands with a Makefile target - e.g., build and deploy a container. make test_cronjob - Examine the log to check whether your job is successful:
sudo cat /tmp/script-output.log - Once your test job is successful, edit your Cron file or scripts to call the actual job you want to run.
- Update the job execution frequency from
* * * * *to something more reasonable, like0 0 * * 0(every Sunday at midnight).
Hope that saved you a few minutes of Googling.
