Cron runs commands at set times: a nightly backup, a cleanup, a report. It is built into every Linux server. The most common problem is a job that looks right but never runs, so this guide also shows how to check.
Before you start, connect to your VPS with SSH.
1. How a schedule is written
A cron line has five time fields, then the command:
minute hour day-of-month month day-of-week command
Examples:
30 2 * * *at 02:30 every day*/15 * * * *every 15 minutes0 9 * * 1at 09:00 every Monday0 0 1 * *at midnight on the first day of each month
The server's time zone decides what "02:30" means. Check it with timedatectl. Most VPS servers use UTC; India is UTC plus 5 hours 30 minutes.
2. Add a job
crontab -e
Choose an editor if asked, then add a line at the bottom:
30 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
The >> /var/log/cleanup.log 2>&1 part saves the output and the errors to a file. Without it you will never see why a job failed. Save and exit.
3. Make the script safe to run
sudo chmod 700 /usr/local/bin/cleanup.sh
Start the script with #!/bin/bash. Always write full paths to programs and files, because cron does not use your usual search path. For example, write /usr/bin/node and not just node.
4. Check that it ran
crontab -l
grep CRON /var/log/syslog | tail -n 10
tail -n 20 /var/log/cleanup.log
If you see your command in the syslog but nothing happens, run the exact command by hand and read the error.
5. Common reasons a job does not run
- The script is not executable, or the path is wrong.
- A program is not found because the path was not full.
- The percent sign
%has a special meaning in cron; write\%in dates, for exampledate +\%F. - The job uses a password or environment variable that exists only in your own login. Put the values inside the script, in a file that only that user can read.
- The server was off or rebooting at the scheduled time.
Good to know
- Run a job as the user it belongs to. Use
sudo crontab -eonly for jobs that need root. - For a job that must also run after a missed time, use a systemd timer with
Persistent=trueinstead of cron.
Run it on your own VPS
Cloud VPS plans: An always-on server for your scheduled jobs. Prices are in rupees, you can pay by UPI, and you get a GST invoice.