Linux

Chapter 13: Scheduled Tasks and Cron Jobs in WSL Ubuntu

Chapter 13: Scheduled Tasks and Cron Jobs in WSL Ubuntu

Automation is one of the most powerful features of Linux. Cron jobs allow you to schedule scripts or commands to run automatically at specified times or intervals in WSL Ubuntu.

In this chapter, you’ll learn how to view, create, and manage cron jobs for recurring tasks.

๐Ÿ•’ What Is Cron?

Cron is a Linux utility used to schedule commands or scripts to run periodically. Each user can have their own cron jobs.

๐Ÿ“Œ Viewing Current Cron Jobs

crontab -l

Displays all scheduled jobs for the current user.

๐Ÿ“Œ Editing Cron Jobs

crontab -e

This opens the cron table in your default text editor (nano, vim, etc.).

๐Ÿ“… Cron Job Syntax

# โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ minute (0 - 59)
# โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€ hour (0 - 23)
# โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€ day of month (1 - 31)
# โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€ month (1 - 12)
# โ”‚ โ”‚ โ”‚ โ”‚ โ”Œ day of week (0 - 6) (Sunday=0)
# โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
# * * * * * command_to_execute

Examples:

  • Run a script every day at 5 AM:
    0 5 * * * /home/umar/backup.sh
  • Run a command every 15 minutes:
    */15 * * * * /home/umar/check_logs.sh
  • Run a script every Monday at 2 PM:
    0 14 * * 1 /home/umar/weekly_report.sh

๐Ÿ“Œ Managing Cron Jobs

Delete All Cron Jobs

crontab -r

View Cron Jobs for Another User

sudo crontab -u username -l

Edit Cron Jobs for Another User

sudo crontab -u username -e

๐Ÿงช Practical Exercises

# Schedule a backup script every day at midnight
0 0 * * * /home/umar/backup.sh

# Schedule a log cleanup script every 2 hours
0 */2 * * * /home/umar/cleanup_logs.sh

# Schedule a system update every Sunday at 3 AM
0 3 * * 0 sudo apt update && sudo apt upgrade -y

โœ… Summary

  • Cron allows automation of commands and scripts at scheduled times
  • crontab -l โ€“ View current cron jobs
  • crontab -e โ€“ Edit cron jobs
  • crontab -r โ€“ Remove all cron jobs
  • Use proper syntax to define minute, hour, day, month, and day of week
  • Automate backups, maintenance, updates, and repetitive tasks

โ–ถ๏ธ Coming Up Next

Chapter 14 โ€“ Package Management in WSL Ubuntu
Learn how to install, update, and remove software packages using apt and manage repositories effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *