Running tasks automatically at set times (cron)
Here's how to run commands automatically at set times, like "back up every day at 4 a.m.", "check status every 10 minutes" or "start the bot when the server starts". This guide is based on Ubuntu/Debian.
First, set the server to Korea time
cron works on the server's time zone. If the server is set to UTC (9 hours behind Korea), "4 a.m." becomes 1 p.m. Korea time.
timedatectl # Check the Time zone line
sudo timedatectl set-timezone Asia/Seoul # Change to Korea time
sudo systemctl restart cron # Restart cron so it uses the new time zone
Open crontab
crontab -e
The first time you run it, you'll be asked to choose an editor; nano (usually option 1) is the easiest. Add each job you want to schedule as one line at the very bottom, then save and exit with Ctrl + O, Enter, Ctrl + X.
How to write the time
minute hour day month weekday command
| How to write it | Meaning |
|---|---|
0 4 * * * | Every day at 4 a.m. |
*/10 * * * * | Every 10 minutes |
0 */6 * * * | Every 6 hours (0:00, 6:00, 12:00, 18:00) |
30 9 * * 1 | Every Monday at 9:30 a.m. |
0 0 1 * * | Midnight on the 1st of every month |
@reboot | Once, when the server starts |
If it's confusing, enter it on the crontab.guru site and it will spell out in words when it runs.
Examples
# Restart the bot run with pm2 every day at 5 a.m.
0 5 * * * /usr/bin/pm2 restart my-bot >> /home/username/cron.log 2>&1
# Run my script when the server starts
@reboot /home/username/start.sh >> /home/username/cron.log 2>&1
For scheduling backups, see "Back up automatically every day" in Backing up your server data.
Rules to follow
- Write commands and files with full paths. cron's environment is different from your usual terminal, so if you write just
pm2ornode, it often can't find them. Check the full paths withwhich pm2andwhich node. - Save the output to a log file. Adding
>> /home/username/cron.log 2>&1at the end of the line lets you see why it failed. - Give scripts execute permission.
chmod +x start.sh - Write
%in commands as\%. cron reads%as a line break. (e.g.,$(date +\%F)) - Jobs that need administrator privileges (rebooting the server, etc.) go in
sudo crontab -e.
Check that it's registered
crontab -l # Show registered jobs
journalctl -u cron --since today # Today's cron run history
On a Windows server
On Windows, "Task Scheduler" does the same job. See Running programs automatically on a Windows server.