Chapter 6: A Comprehensive Guide to Using Cronjobs

by Reza Lavaryan

Terminology

Getting Started

run-parts

Crontab Files

0 0 * * *  /var/www/sites/db_backup.sh

spool Directory Location

crontab -e
    
export VISUAL=nano; crontab -e

Privileges

crontab -l
crontab /path/to/the/file/containing/cronjobs.txt
crontab -r

Anatomy of a Crontab Entry

# ┌───────────── min (0 - 59) 
 # │ ┌────────────── hour (0 - 23)
 # │ │ ┌─────────────── day of month (1 - 31)
 # │ │ │ ┌──────────────── month (1 - 12)
 # │ │ │ │ ┌───────────────── day of week (0 - 6) 
 # │ │ │ │ │
 # │ │ │ │ │
 # * * * * *  command to execute    
0 0 5-20/5 Feb 2 /path/to/command

Specifying Both Day of Month and Day of Week

* * * * * testuser /path/to/command

Editing Other Users’ Crontab

crontab -u username -e
    

Privileges

sudo crontab -e
    

Ownership

man crontab

Standard and Non-Standard Values

Ranges

0 6-18 1-15 * * /path/to/command

Lists

0 1,4,5,7 * * * /path/to/command

Steps

0 6-18/2 * * * /path/to/command
0 0-10/5,14,15,18-23/3 1 1 * /path/to/command

Names

* * * Feb,mar sat,sun /path/to/command

Predefined Definitions

  • @yearly, @annually Run once a year at midnight of January 1 (0 0 1 1 *)
  • @monthly Run once a month, at midnight of the first day of the month (0 0 1 * *)
  • @weekly Run once a week at midnight of Sunday (0 0 * * 0)
  • @daily Run once a day at midnight (0 0 * * *)
  • @hourly Run at the beginning of every hour (0 * * * *)
  • @reboot Run once at startup

Multiple Commands in the Same Cron Job

* * * * * /path/to/command-1; /path/to/command-2
* * * * * /path/to/command-1 && /path/to/command-2

Environment Variables

PATH = /usr/bin;/usr/local/bin

Use Quote Marks

Different Time Zones

How Cron Interprets Crontab Files

Cron Permissions

echo ALL > /etc/cron.deny

Allow and Deny

Redirecting Output

* * * * * /path/to/php /path/to/the/command >> /var/log/cron.log
* * * * * /path/to/php /path/to/the/command > /dev/null
* * * * * /path/to/php /path/to/the/command > /dev/null 2>&1

Email the Output

[email protected],[email protected]
* * * * * /path/to/command

Cron and PHP

php script.php
#! /usr/bin/php

<?php

// PHP code here

Task Overlaps

Using Flock

apt-get install flock
yum install flock
* * * * * /usr/bin/flock --timeout=1 /path/to/cron.lock /usr/bin/php /path/to/scripts.php

Using a Locking Mechanism in the Scripts

<?php
$lockfile = sys_get_temp_dir() . '/' md5(__FILE__) . '.lock';
$pid      = file_exists($lockfile) ? trim(file_get_contents($lockfile)) : null;

if (is_null($pid) || posix_getsid($pid) === false) {

    // Do something here
    
    // And then create/update the lock file
    file_put_contents($lockfile, getmypid());

} else {
    exit('Another instance of the script is already running.');
}

Anacron

# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1       5       cron.daily              nice run-parts /etc/cron.daily
7       25      cron.weekly             nice run-parts /etc/cron.weekly
@monthly 45     cron.monthly            nice run-parts /etc/cron.monthly
1       5       cron.daily              nice run-parts /etc/cron.daily

Collision Between Cron and Anacron

Quick Troubleshooting

Absolute Path to the commands

* * * * * /usr/local/bin/php /absolute/path/to/the/command

Make Sure Cron Daemon Is Running

ps aux | grep crond
root      7481  0.0  0.0 116860  1180 ?        Ss    2015   0:49 crond

Check /etc/cron.allow and /etc/cron.deny Files

Execute Permission

New Line Character

Wrapping Up

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.119.220