Making a cron job

This is how I did my first cron job (pasted in from this web site: http://www.unixgeeks.org/security/newbie/unix/cron-1.html )

Found a better one here: http://www.sitepoint.com/a-comprehensive-crash-course-into-cronjobs/
...which is entirely pasted as a comment below this article.

ALSO IMPORTANT: In the crontab itself (at sudo vi /etc/crontab), you must specify the path *running* the program; for example: /usr/bin/java or /usr/bin/php Those are probably links to the binaries or whatever there in /usr/bin... SEE EXISTING crontab FOR GOOD EXAMPLES.

Newbie: Intro to cron
Date: 30-Dec-99
Author: cogNiTioN <cognition@attrition.org>

Cron

This file is an introduction to cron, it covers the basics of what cron does,
and how to use it.

What is cron?

Cron is the name of program that enables unix users to execute commands or
scripts (groups of commands) automatically at a specified time/date. It is
normally used for sys admin commands, like makewhatis, which builds a
search database for the man -k command, or for running a backup script, 
but can be used for anything. A common use for it today is connecting to 
the internet and downloading your email.

This file will look at Vixie Cron, a version of cron authored by Paul Vixie.

How to start Cron

Cron is a daemon, which means that it only needs to be started once, and will 
lay dormant until it is required. A Web server is a daemon, it stays dormant 
until it gets asked for a web page. The cron daemon, or crond, stays dormant 
until a time specified in one of the config files, or crontabs.

On most Linux distributions crond is automatically installed and entered into 
the start up scripts. To find out if it's running do the following:

cog@pingu $ ps aux | grep crond
root       311  0.0  0.7  1284  112 ?        S    Dec24   0:00 crond
cog       8606  4.0  2.6  1148  388 tty2     S    12:47   0:00 grep crond

The top line shows that crond is running, the bottom line is the search
we just run.

If it's not running then either you killed it since the last time you rebooted,
or it wasn't started.

To start it, just add the line crond to one of your start up scripts. The 
process automatically goes into the back ground, so you don't have to force
it with &. Cron will be started next time you reboot. To run it without 
rebooting, just type crond as root:

root@pingu # crond

With lots of daemons, (e.g. httpd and syslogd) they need to be restarted 
after the config files have been changed so that the program has a chance 
to reload them. Vixie Cron will automatically reload the files after they 
have been edited with the crontab command. Some cron versions reload the
files every minute, and some require restarting, but Vixie Cron just loads 
the files if they have changed.

Using cron

There are a few different ways to use cron (surprise, surprise). 

In the /etc directory you will probably find some sub directories called 
'cron.hourly', 'cron.daily', 'cron.weekly' and 'cron.monthly'. If you place 
a script into one of those directories it will be run either hourly, daily, 
weekly or monthly, depending on the name of the directory. 

If you want more flexibility than this, you can edit a crontab (the name 
for cron's config files). The main config file is normally /etc/crontab.
On a default RedHat install, the crontab will look something like this:

root@pingu # cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * 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 part is almost self explanatory; it sets the variables for cron.

SHELL is the 'shell' cron runs under. If unspecified, it will default to 
the entry in the /etc/passwd file.

PATH contains the directories which will be in the search path for cron 
e.g if you've got a program 'foo' in the directory /usr/cog/bin, it might 
be worth adding /usr/cog/bin to the path, as it will stop you having to use
the full path to 'foo' every time you want to call it.

MAILTO is who gets mailed the output of each command. If a command cron is 
running has output (e.g. status reports, or errors), cron will email the output 
to whoever is specified in this variable. If no one if specified, then the 
output will be mailed to the owner of the process that produced the output.

HOME is the home directory that is used for cron. If unspecified, it will 
default to the entry in the /etc/passwd file.

Now for the more complicated second part of a crontab file.
An entry in cron is made up of a series of fields, much like the /etc/passwd
file is, but in the crontab they are separated by a space. There are normally
seven fields in one entry. The fields are:

minute hour dom month dow user cmd

minute	This controls what minute of the hour the command will run on,
	 and is between '0' and '59'
hour	This controls what hour the command will run on, and is specified in
         the 24 hour clock, values must be between 0 and 23 (0 is midnight)
dom	This is the Day of Month, that you want the command run on, e.g. to
	 run a command on the 19th of each month, the dom would be 19.
month	This is the month a specified command will run on, it may be specified
	 numerically (0-12), or as the name of the month (e.g. May)
dow	This is the Day of Week that you want a command to be run on, it can
	 also be numeric (0-7) or as the name of the day (e.g. sun).
user	This is the user who runs the command.
cmd	This is the command that you want run. This field may contain 
	 multiple words or spaces.

If you don't wish to specify a value for a field, just place a * in the 
field.

e.g.
01 * * * * root echo "This command is run at one min past every hour"
17 8 * * * root echo "This command is run daily at 8:17 am"
17 20 * * * root echo "This command is run daily at 8:17 pm"
00 4 * * 0 root echo "This command is run at 4 am every Sunday"
* 4 * * Sun root echo "So is this"
42 4 1 * * root echo "This command is run 4:42 am every 1st of the month"
01 * 19 07 * root echo "This command is run hourly on the 19th of July"

Notes:

Under dow 0 and 7 are both Sunday.

If both the dom and dow are specified, the command will be executed when
either of the events happen. 
e.g.
* 12 16 * Mon root cmd
Will run cmd at midday every Monday and every 16th, and will produce the 
same result as both of these entries put together would:
* 12 16 * * root cmd
* 12 * * Mon root cmd

Vixie Cron also accepts lists in the fields. Lists can be in the form, 1,2,3 
(meaning 1 and 2 and 3) or 1-3 (also meaning 1 and 2 and 3).
e.g.
59 11 * * 1,2,3,4,5 root backup.sh
Will run backup.sh at 11:59 Monday, Tuesday, Wednesday, Thursday and Friday,
as will:
59 11 * * 1-5 root backup.sh 

Cron also supports 'step' values.
A value of */2 in the dom field would mean the command runs every two days
and likewise, */5 in the hours field would mean the command runs every 
5 hours.
e.g. 
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

*/15 9-17 * * * root connection.test
Will run connection.test every 15 mins between the hours or 9am and 5pm

Lists can also be combined with each other, or with steps:
* 12 1-15,17,20-25 * * root cmd
Will run cmd every midday between the 1st and the 15th as well as the 20th 
and 25th (inclusive) and also on the 17th of every month.
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

When using the names of weekdays or months, it isn't case sensitive, but only
the first three letters should be used, e.g. Mon, sun or Mar, jul.

Comments are allowed in crontabs, but they must be preceded with a '#', and
must be on a line by them self.  


Multiuser cron

As Unix is a multiuser OS, some of the apps have to be able to support 
multiple users, cron is one of these. Each user can have their own crontab
file, which can be created/edited/removed by the command crontab. This
command creates an individual crontab file and although this is a text file,
as the /etc/crontab is, it shouldn't be edited directly. The crontab file is
often stored in /var/spool/cron/crontabs/<user> (Unix/Slackware/*BSD), 
/var/spool/cron/<user> (RedHat) or /var/cron/tabs/<user> (SuSE), 
but might be kept elsewhere depending on what Un*x flavor you're running.

To edit (or create) your crontab file, use the command crontab -e, and this
will load up the editor specified in the environment variables EDITOR or 
VISUAL, to change the editor invoked on Bourne-compliant shells, try: 
cog@pingu $ export EDITOR=vi
On C shells:
cog@pingu $ setenv EDITOR vi
You can of course substitute vi for the text editor of your choice.

Your own personal crontab follows exactly the same format as the main
/etc/crontab file does, except that you need not specify the MAILTO 
variable, as this entry defaults to the process owner, so you would be mailed
the output anyway, but if you so wish, this variable can be specified.
You also need not have the user field in the crontab entries. e.g.

min hr dom month dow cmd

Once you have written your crontab file, and exited the editor, then it will
check the syntax of the file, and give you a chance to fix any errors.

If you want to write your crontab without using the crontab command, you can
write it in a normal text file, using your editor of choice, and then use the
crontab command to replace your current crontab with the file you just wrote.
e.g. if you wrote a crontab called cogs.cron.file, you would use the cmd

cog@pingu $ crontab cogs.cron.file

to replace your existing crontab with the one in cogs.cron.file.

You can use 

cog@pingu $ crontab -l 

to list your current crontab, and

cog@pingu $ crontab -r

will remove (i.e. delete) your current crontab.

Privileged users can also change other user's crontab with:

root@pingu # crontab -u 
and then following it with either the name of a file to replace the 
existing user's crontab, or one of the -e, -l or -r options.

According to the documentation the crontab command can be confused by the 
su command, so if you running a su'ed shell, then it is recommended you 
use the -u option anyway.

Controlling Access to cron

Cron has a built in feature of allowing you to specify who may, and who 
may not use it. It does this by the use of /etc/cron.allow and /etc/cron.deny
files. These files work the same way as the allow/deny files for other 
daemons do. To stop a user using cron, just put their name in cron.deny, to
allow a user put their name in the cron.allow. If you wanted to prevent all
users from using cron, you could add the line ALL to the cron.deny file:

root@pingu # echo ALL >>/etc/cron.deny

If you want user cog to be able to use cron, you would add the line cog 
to the cron.allow file:

root@pingu # echo cog >>/etc/cron.allow

If there is neither a cron.allow nor a cron.deny file, then the use of cron
is unrestricted (i.e. every user can use it).  If you were to put the name of
some users into the cron.allow file, without creating a cron.deny file, it
would have the same effect as creating a cron.deny file with ALL in it.
This means that any subsequent users that require cron access should be 
put in to the cron.allow file.  

Output from cron

As I've said before, the output from cron gets mailed to the owner of the
process, or the person specified in the MAILTO variable, but what if you
don't want that? If you want to mail the output to someone else, you can
just pipe the output to the command mail.
e.g.
 
cmd | mail -s "Subject of mail" user

If you wish to mail the output to someone not located on the machine, in the
above example, substitute user for the email address of the person who 
wishes to receive the output.

If you have a command that is run often, and you don't want to be emailed 
the output every time, you can redirect the output to a log file (or 
/dev/null, if you really don't want the output).
e,g

cmd >> log.file

Notice we're using two > signs so that the output appends the log file and 
doesn't clobber previous output.
The above example only redirects the standard output, not the standard error,
if you want all output stored in the log file, this should do the trick:

cmd >> logfile 2>&1

You can then set up a cron job that mails you the contents of the file at
specified time intervals, using the cmd:

mail -s "logfile for cmd" <log.file
 

Now you should be able to use cron to automate things a bit more.
A future file going into more detail, explaining the differences between 
the various different crons and with more worked examples, is planned.


Additional Reference:

Man pages: cron(8) crontab(5) crontab(1)

Book: _Running Linux_ (O'Reilly ISBN: 1-56592-469-X)


cog

© Copyright 2000 cogNiTioN <cognition@attrition.org>

Comments

There are times when there’s a need for running a group of tasks automatically at certain times in the future. These tasks are usually administrative, but could be anything – from making database backups to downloading emails when everyone is asleep.
Cron is a time-based job scheduler in Unix-like operating systems, which triggers certain tasks at a point in the future. The name originates from the Greek word χρόνος (chronos), which means time.

More from this author

The most commonly used version of Cron is known as Vixie Cron, originally developed by Paul Vixie in 1987.
This article is an in-depth walkthrough of this program, and a reboot of this ancient, but still surprisingly relevant post.

Terminology

  • Job: a unit of work, a series of steps to do something. For example, sending an email to a group of users. In this article, we’ll use task, job, cron job or event interchangeably.
  • Daemon: (/ˈdiːmən/ or /ˈdeɪmən/) is a computer program which runs in the background, serving different purposes. Daemons are often started at boot time. A web server is a daemon serving HTTP requests. Cron is a daemon for running scheduled tasks.
  • Cron Job: a cron job is a scheduled job, being run by Cron when it’s due.
  • Webcron: a time-based job scheduler which runs within the web server environment. It’s used as an alternative to the standard Cron, often on shared web hosts that do not provide shell access.

Getting Started
This tutorial assumes you’re running a Unix-based operating system like Ubuntu. If you aren’t, we recommend setting up Homestead Improved – it’s a 5 minute process which will save you years down the line.
If we take a look inside the /etc directory, we can see directories like cron.hourly, cron.daily, cron.weekly and cron.monthly, each corresponding to a certain frequency of execution. One way to schedule our tasks is to place our scripts in the proper directory. For example, to run db_backup.php on a daily basis, we put it inside cron.daily. If the folder for a given frequency is missing, we would need to create it first.
Note: This approach uses the run-parts script, a command which runs every executable it finds within the specified directory.
This is the simplest way to schedule a task. However, if we need more flexibility, we should use Crontab.
Crontab Files
Cron uses special configuration files called crontab files, which contain a list of jobs to be done. Crontab stands for Cron Table. Each line in the crontab file is called a cron job, which resembles a set of columns separated by a space character. Each row specifies when and how often a certain command or script should be executed.
In a crontab file, blank lines or lines starting with #, spaces or tabs will be ignored. Lines starting with # are considered comments.
Active lines in a crontab are either the declaration of an environment variable or a cron job, and comments are not allowed on the active lines.
Below is an example of a crontab file with just one entry:
0 0 * * * /var/www/sites/db_backup.sh

The first part 0 0 * * * is the cron expression, which specifies the frequency of execution. The above cron job will run once a day.
Users can have their own crontab files named after their username as registered in the /etc/passwd file. All user-level crontab files reside in Cron’s spool area. These files should not be edited directly. Instead, we should edit them using the crontab command-line utility.
Note: The spool directory varies across different distributions of Linux. On Ubuntu it’s /var/spool/cron/crontabs while in CentOS it’s /var/spool/cron.
To edit our own crontab file:
crontab -e

The above command will automatically open up the crontab file which belongs to our user. If a default system editor for the crontab hasn’t been selected before, a choice will be presented listing the installed ones. We can also explicitly choose or change our desired editor for editing the crontab file:
export VISUAL=nano; crontab -e

After we save the file and exit the editor, the crontab will be checked for accuracy. If everything is set properly, the file will be saved to the spool directory.
Note: Each command in the crontab file is executed from the perspective of the user who owns the crontab, so if your command runs as root (sudo) you will not be able to define this crontab from your own user account unless you log in as root.
To list the installed cron jobs belonging to our own user:
crontab -l

We can also write our cron jobs in a file and send its contents to the crontab file like so:
crontab /path/to/the/file/containing/cronjobs.txt

The preceding command will overwrite the existing crontab file with /path/to/the/file/containing/cronjobs.txt.
To remove the crontab, we use the -r option:
crontab -r

Anatomy of a Crontab Entry
The anatomy of a user-level crontab entry looks like the following:
# ┌───────────── min (0 - 59)
# │ ┌────────────── hour (0 - 23)
# │ │ ┌─────────────── day of month (1 - 31)
# │ │ │ ┌──────────────── month (1 - 12)
# │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute

The first two fields specify the time (minute and hour) at which the task will run. The next two fields specify the day of the month and the month. The fifth field specifies the day of the week.
The command will be executed when the minute, hour, month and either day of month or day of week match the current time.
If both day of week and day of month have certain values, the event will be run when either field matches the current time. Consider the following expression:
0 0 5-20/5 Feb 2 /path/to/command

The preceding cron job will run once per day every five days, from 5th to 20th of February plus all Tuesdays of February.
Important: When both day of month and day of week have certain values (not an asterisk), it will create an OR condition, meaning both days will be matched.
The syntax in system crontabs (/etc/crontab) is slightly different than user-level crontabs. The difference is that the sixth field is not the command, but it is the user we want to run the job as.
* * * * * testuser /path/to/command

It’s not recommended to put system-wide cron jobs in /etc/crontab, as this file might be modified in future system updates. Instead, we put these cron jobs in the /etc/cron.d directory.
Editing Other Users’ Crontab
We might need to edit other users’ crontab files. To do this, we use the -u option as below:
crontab -u username -e

Note We can only edit other users’ crontab files as the root user, or as a user with administrative privileges.
Some tasks require super admin privileges, thus, they should be added to the root user’s crontab file:
sudo crontab -e

Note: Please note that using sudo with crontab -e will edit the root user’s crontab file. If we need to to edit another user’s crontab while using sudo, we should use -u option to specify the crontab owner.
To learn more about the crontab command:
man crontab

Standard and Non-Standard Values
Crontab fields accept numbers as values. However, we can put other data structures in these fields, as well.
Ranges
We can pass in ranges of numbers:
0 6-18 1-15 * * /path/to/command

The above cron job will be executed from 6 am to 6 pm from 1st to 15th of each month in the year. Note that the specified range is inclusive, so 1-5 means 1,2,3,4,5.
Lists
A list is a group of values separated by commas. We can have lists as field values:
0 1,4,5,7 * * * /path/to/command

The above syntax will run the cron job at 1 am, 4 am, 5 am and 7 am every day.
Steps
Steps can be used with ranges or the asterisk character (*). When they are used with ranges they specify the number of values to skip through the end of the range. They are defined with a / character after the range, followed by a number. Consider the following syntax:
0 6-18/2 * * * /path/to/command

The above cron job will be executed every two hours from 6 am to 6 pm.
When steps are used with an asterisk, they simply specify the frequency of that particular field. As an example if we set the minute to */5, it simply means every five minutes.
We can combine lists, ranges, and steps together to have more flexible event scheduling:
0 0-10/5,14,15,18-23/3 1 1 * /path/to/command

The above event will run every five hours from midnight of January 1st to 10 am, 2 pm, 3 pm and also every three hours from 6pm to 11 pm.
Names
For the fields month and day of week we can use the first three letters of a particular day or month, like Sat, sun, Feb, Sep, etc.
* * * Feb,mar sat,sun /path/to/command

The preceding cron job will be run only on Saturdays and Sundays of February and March.
Please note that the names are not case-sensitive. Ranges are not allowed when using names.
Predefined Definitions
Some cron implementations may support some special strings. These strings are used instead of the first five fields, each specifying a certain frequency:

  • @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
We can run several commands in the same cron job by separating them with a semi-colon (;).
* * * * * /path/to/command-1; /path/to/command-2

If the running commands depend on each other, we can use double ampersand (&&) between them. As a result, the second command will not be executed if the first one fails.
* * * * * /path/to/command-1 && /path/to/command-2

Environment Variables
Environment variables in crontab files are in the form of VARIABLE_NAME = VALUE (The white spaces around the equal sign are optional). Cron does not source any startup files from the user’s home directory (when it’s running user-level crons). This means we should manually set any user-specific settings required by our tasks.
Cron daemon automatically sets some environmental variables when it starts. HOME and LOGNAME are set from the crontab owner’s information in /etc/passwd. However, we can override these values in our crontab file if there’s a need for this.
There are also a few more variables like SHELL, specifying the shell which runs the commands. It is /bin/sh by default. We can also set the PATH in which to look for programs.
PATH = /usr/bin;/usr/local/bin

Important: We should wrap the value in quotation marks when there’s a space in the value. Please note that values are considered as ordinary strings and are not interpreted or parsed in any way.
Different Time Zones
Cron uses the system’s time zone setting when evaluating crontab entries. This might cause problems for multiuser systems with users based in different time zones. To work around this problem, we can add an environment variable named CRON_TZ in our crontab file. As a result, all crontab entries will be parsed based on the specified timezone.
How Cron Interprets Crontab Files
After Cron starts, it searches its spool area to find and load crontab files into the memory. It additionally checks the /etc/crontab and or /etc/cron.d directories for system crontabs.
After loading the crontabs into memory, Cron checks the loaded crontabs on a minute-by-minute basis, running the events which are due.
In addition to this, Cron regularly (every minute) checks if the spool directory’s modtime (modification time) has changed. If so, it checks the modetime of all the loaded crontabs and reloads those which have changed. That’s why we don’t have to restart the daemon when installing a new cron job.
Cron Permissions
We can specify which user should be able to use Cron and which user should not. There are two files which play an important role when it comes to cron permissions: /etc/cron.allow and /etc/cron.deny.
If /etc/cron.allow exists, then our username must be listed in this file in order to use crontab. If /etc/cron.deny exists, it shouldn’t contain our username. If neither of these files exist, then based on the site-dependent configuration parameters, either the super user or all users will be able to use crontab command. For example, in Ubuntu, if neither file exists, all users can use crontab by default.
We can put ALL in /etc/cron.deny file to prevent all users from using cron:
echo ALL > /etc/cron.deny

Note: If we create an /etc/cron.allow file, there’s no need to create a /etc/cron.deny file as it has the same effect as creating a /etc/cron.deny file with ALL in it.
Redirecting Output
We can redirect the output of our cron job to a file, if the command (or script) has any output:
* * * * * /path/to/php /path/to/the/command >> /var/log/cron.log

We can redirect the standard output to dev null, to get no email (more on emails below), but still allowing the standard error to be sent as email:
* * * * * /path/to/php /path/to/the/command > /dev/null

To prevent Cron from sending any emails to us, we change the respective crontab entry as below:
* * * * * /path/to/php /path/to/the/command > /dev/null 2>&1

This means “send both the standard output, and the error output into oblivion”.
Email the Output
The output is mailed to the owner of the crontab or the email(s) specified in the MAILTO environment variable (if the standard output or standard error are not redirected as above).
If MAILTO is set to empty, no email will be sent out as the result of the cron job.
We can set several emails by separating them with commas:
MAILTO=admin@example.com,dev@example.com
* * * * * /path/to/command

Cron and PHP
We usually run our PHP command line scripts using the PHP executable.
php script.php

Alternatively, we can use shebang at the beginning of the script, and point to the PHP executable:
#! /usr/bin/php

<?php

// PHP code here

As a result, we can execute the file by calling it by name. However, we need to make sure we have the permission to execute it.
To have more robust PHP command line scripts, we can use third-party components for creating console applications like Symfony Console Component or Laravel Artisan. This article is a good start for using Symfony’s Console Component.
Creating console commands using Laravel Artisan has been also covered here. If you’d rather use another command line tool for PHP, we have a comparison here.
Task Overlaps
There are times when scheduled tasks take much longer than expected. This will cause overlaps, meaning some tasks might be running at the same time. This might not cause a problem in some cases, but when they are modifying the same data in a database, we’ll have a problem. We can overcome this by increasing the execution frequency of the tasks, but still it’s not guaranteed that these overlaps won’t happen again.
We have several options to prevent cron jobs from overlapping.
Using Flock
Flock is a nice tool to manage lock files from within shell scripts or the command line. These lock files are useful for knowing whether or not a script is running.
When used in conjunction with Cron, the respective cron jobs do not start if the lock file exists. You can install Flock using apt-get or yum depending on the Linux distribution.
apt-get install flock

Or
yum install flock

Consider the following crontab entry:
* * * * * /usr/bin/flock --timeout=1 /path/to/cron.lock /usr/bin/php /path/to/scripts.php

In the preceding example, flock looks for /path/to/cron.lock. If the lock is acquired in one second, it will run the script, otherwise, it will fail with an exit code of 1.
Using a Locking Mechanism in the Scripts
If the cron job executes a script, we can implement a locking mechanism in the script. Consider the following PHP script:
<?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.');
}

In the preceding code, we keep pid of the current PHP process in a file, which is located in the system’s temp directory. Each PHP script has its own lock file, which is the MD5 hash of the script’s filename.
First, we check if the lock file exists, and then we get its content, which is the process ID of the last running instance of the script. Then we pass the pid to posix_getsid PHP function, which returns the session ID of the process. If posix_getsid returns false it means the process is not running anymore and we can safely start a new instance.
Anacron
One of the problems with Cron is that it assumes the system is running continuously (24 hours a day). This causes problems for machines which are not running all day long (like personal computers). If the system goes off during the time a task is scheduled to run, Cron will not run that task retroactively.
Anacron is not a replacement for Cron, but it has been developed to solve this problem. It runs the commands once a day, week or month but not on a minute-by-minute or hourly basis as Cron does. It is, however, guaranteed that the task will run even if the system goes off for an unanticipated period of time.
Only root or a user with administrative privileges can manage Anacron tasks. Anacron does not run in the background like a daemon, but only once, executing the tasks which are due.
Anacron uses a configuration file (just like crontab) named anacrontabs. This file is located in the /etc directory.
The content of this file looks like this:
# /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

In an anacrontab file, we can only set the frequencies with a period of n days, followed by the delay time in minutes. This delay time is just to make sure the tasks do not run at the same time.
The third column is a unique name, which is used to identify the task in the Anacron log files.
The fourth column is the actual command to be run.
Consider the following entry:
1 5 cron.daily nice run-parts /etc/cron.daily

The above tasks are run daily, 5 minutes after Anacron is run. It uses run-parts to execute all the scripts within /etc/cron.daily.
The second entry in the list above runs every 7 days (weekly), with a 25 minutes delay.
Collision Between Cron and Anacron
As you have probably noticed, Cron is also set to execute the scripts inside /etc/cron.* directories. This sort of possible collision with Anacron is handled differently in different flavors of Linux. In Ubuntu, Cron checks if Anacron is present in the system, and if it so, it won’t execute the scripts within /etc/cron.* directories.
In other flavors of Linux, Cron updates the Anacron times-stamps when it runs the tasks, so Anacron won’t execute them if they have been already run by Cron.
Quick Troubleshooting
Absolute Path to the commands
It’s a good habit to use the absolute paths to all the executables we use in a crontab file.
* * * * * /usr/local/bin/php /absolute/path/to/the/command

Make Sure Cron Daemon Is Running
If our tasks are not running at all, first we need to make sure the Cron daemon is running:
ps aux | grep crond

The output should similar to this:
root 7481 0.0 0.0 116860 1180 ? Ss 2015 0:49 crond

Check /etc/cron.allow and /etc/cron.deny Files
If the cron jobs are not running, then we need to check if /etc/cron.allow exists. If it does, we need to make sure our username is listed in this file. If /etc/cron.deny exists, we need to make sure our username is not listed in this file.
If we edit a user’s crontab file whereas the user does not exist in the /etc/cron.allow file, including the user in the /etc/cron.allow won’t run the cron until we re-edit the crontab file.
Execute Permission
We need to make sure that the owner of the crontab has the execute permissions for all the commands and scripts in the crontab file. Otherwise, the cron will not work. Execute permissions can be added to any folder or file with chmod +x /some/file.php
New Line Character
Every entry in the crontab should end with a new line. This means there must be a blank line after the last crontab entry, or the last cron job will never run.
Wrapping Up
Cron is a daemon, running a list of events scheduled to take place in the future. These jobs are listed in special configuration files called crontab files. Users can have their own crontab file, if they are allowed to use Cron, based on /etc/cron.allow or /etc/cron.deny files. In addition to user-level cron jobs, Cron also loads the system-wide cron jobs which are slightly different in syntax.
Our tasks are commonly PHP scripts or command-line utilities. In systems which are not running all the time, we can use Anacron to run the events which happen in the period of n days.
When working with Cron, we should also be aware of the tasks overlapping each other, to prevent data loss. After a cron job is finished, the output will be sent to the owner of the crontab and or the email(s) specified in the MAILTO environment variable.
Did you learn anything new from this post? Have we missed anything? Or did you just like this post and want to tell us how awesomely comprehensive it was? Let us know in the comments below!