Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Linux Crontab Command: Complete Guide to Scheduled Tasks

Tech Aug 3 2

Overview

The crond daemon is a background process in Linux that executes scheduled tasks at specified intervals, similar to the Task Scheduler in Windows. After installing the operating system, this service is typically pre-installed and automatically starts. The crond process checks every minute for pending tasks and executes them if found.

Linux implements two types of task scheduling:

System Task Scheduling

System tasks run periodically to perform maintenance operations such as clearing cache data to disk or cleaning log files. The system task configuration is stored in /etc/crontab:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
HOME=/

51 * * * * root run-parts /etc/cron.hourly
24 7 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

The first four lines configure environment variables for scheduled tasks: SHELL specifies the shell interpreter (bash), PATH defines command search directories, MAILTO determines where task output gets sent via email (empty value disables notifications), and HOME sets the working directory.

User Task Scheduling

Users can schedule recurring tasks like data backups or automated reports using the crontab utility. User crontab files reside in /var/spool/cron, with filenames matching usernames.

Permission Configuration

File Purpose
/etc/cron.deny Users listed here cannot use crontab
/etc/cron.allow Users listed here can use crontab (takes precedence)
/var/spool/cron/ Directory storing all user crontab files

Crontab Format

Each crontab line represents one scheduled task with six fields:

minute hour day month week command

Field Ranges:

  • minute: 0-59
  • hour: 0-23
  • day: 1-31
  • month: 1-12
  • week: 0-7 (0 and 7 both represent Sunday)

Special Characters:

  • *: Matches any value
  • ,: Specifies a list (e.g., 1,3,5)
  • -: Defines a range (e.g., 2-5 means 2,3,4,5)
  • /: Sets frequency interval (e.g., */10 means every 10 units)

Service Management

Installation:

yum install crontabs

Service Commands:

/sbin/service crond start
/sbin/service crond stop
/sbin/service crond restart
/sbin/service crond reload

Check Status:

service crond status

Enable on Boot:

chkconfig --level 35 crond on

Crontab Command Usage

Syntax:

crontab [-u user] file
crontab [-u user] [-e | -l | -r]

Parameters:

  • -u user: Specifies which user's crontab to manage (requires root privileges)
  • -e: Edit crontab file
  • -l: List current crontab entries
  • -r: Remove crontab file
  • -i: Require confirmation before deletion

Creating a Crontab File

First, set the preferred editor in your profile:

EDITOR=vim
export EDITOR

Create a file with task definitions:

# Monitor system every 15 minutes between 6pm and 6am
0,15,30,45 18-06 * * * /bin/echo 'System check' > /dev/console

Submit the file to cron:

crontab mytasks.cron

Common Operations

List current crontab:

crontab -l

Edit crontab:

crontab -e

Remove crontab:

crontab -r

Restore from backup:

crontab /home/username/backup.cron

Practical Examples

# Execute every minute
* * * * * /path/to/script.sh

# Run at minute 3 and 15 of every hour
3,15 * * * * /path/to/command

# Execute during hours 8-11 at minutes 3 and 15
3,15 8-11 * * * /path/to/command

# Run every 2 days at 8am
0 8 */2 * * /path/to/command

# Execute every Monday at 8am
0 8 * * 1 /path/to/command

# Restart service daily at 9:30 PM
30 21 * * * /etc/init.d/service restart

# Restart on 1st, 10th, and 22nd of each month at 4:45 AM
45 4 1,10,22 * * /etc/init.d/service restart

# Restart on weekends at 1:10 AM
10 1 * * 6,0 /etc/init.d/service restart

# Restart every 30 minutes between 6pm and 11pm
0,30 18-23 * * * /etc/init.d/service restart

# Execute every Saturday at 11 PM
0 23 * * 6 /etc/init.d/service restart

# Restart every hour
* */1 * * * /etc/init.d/service restart

# Restart hourly between 11 PM and 7 AM
* 23-7/1 * * * /etc/init.d/service restart

# Restart at 11 AM on the 4th of each month or on Mon-Wed
0 11 4 * mon-wed /etc/init.d/service restart

# Restart at 4 AM on January 1st
0 4 1 jan * /etc/init.d/service restart

# Run hourly scripts from directory
01 * * * * root run-parts /etc/cron.hourly

Important Considerations

Environment Variables

When running tasks through cron, the environment differs from interactive shells. Scripts must either use absolute paths or explicitly set environment variables:

#!/bin/bash
source /etc/profile
export APP_HOME=/opt/application
export CONFIG_PATH=/etc/app/config.conf
/usr/local/bin/startup.sh

Within crontab, source the profile before execution:

0 * * * * . /etc/profile; /bin/sh /opt/app/scripts/main.sh

Managing Output

Each task generates email notifications that accumulate over time. Redirect output to prevent disk space issues:

0 */3 * * * /usr/local/apache2/apachectl restart >/dev/null 2>&1

This redirects both standard outpput and standard error to the null device.

System vs User Tasks

System-level tasks in /etc/crontab handle maintenance operatiosn. User tasks are stored individually. Root can manage any user's crontab using the -u flag. For system-wide schedules like scehduled reboots, edit /etc/crontab directly.

Troubleshooting

  • Newly created tasks require up to 2 minutes before first execution
  • If tasks fail to run, restart the service: /etc/init.d/crond restart
  • Check logs for errors: tail -f /var/log/cron
  • Use crontab -r with caution—it permanently deletes all scheduled tasks

The percent symbol (%) has special meaning in crontab (represents newline). Escape it with backslashes when used in commands:

# Wrong:
0 0 * * * /path/to/backup.sh date +%Y%m%d

# Correct:
0 0 * * * /path/to/backup.sh date +\%Y\%m\%d

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.