Getting Started

Summary: Cron Jobs are used to automating several tasks, whether its sending newsletter, backing up the SQL database, scheduling a code snippet or maintaining the health of the system. These automated jobs found to be very helpful for the server side.

Cron Jobs in PHP, Creation and its Use

This post refers to the use and creation of our own Cron Jobs, thus simplifying developers hectic work to schedule tasks at a particular time.

Cron Jobs is a Linux utility which schedules a command or script on your server to run automatically at a specified time and date. It is useful for setting up repetitive tasks.

Creation of Cron Jobs in PHP

Some hosting sites provide their own cron job adding a module, use this if possible, the raw method is described here.

Creation of PHP cron jobs via PHP-SSH2 library, PHP provides a way to schedule and create CronTabs via SSH2 library, so priory install SSH2 library as

download the php-ssh2 package from http://pecl.php.net/package/ssh2:

tar vxzf ssh2-0.11.3
cd ssh2-0.11.3
phpize
./configure --with-ssh2
make
make install

and the ssh2. so file will copy into /usr/lib64/php/modules
check it.

Visit here for installation problems if any https://www.php.net/manual/en/ssh2.installation.php

All prerequisite set now moving to understand of CronJob scheduling syntax

* * * * * home/path/to/command/the_command.sh

Let’s break it down here each * represents

Minutes [0-59]

|   Hours [0-23]

|   |   Days [1-31]

|   |   |   Months [1-12]

|   |   |   |   Days of the Week [Numeric, 0-6]

|   |   |   |   |

*   *   *   *   * home/path/to/command/the_command.sh

Declare the following properties of

$connection represents our connection / resource.

$path will represent the path for that file.

$handle will represent the name of our temporary cron file.

$cron_file represents the full path and name of the temporary cron file.

The abstract of the construct function is here as

<?php

Class Ssh2_crontab_manager {

    private $connection;

    private $path;

    private $handle;

    private $cron_file;

    function __construct() {...}

    public function exec() {...}

    public function write_to_file() {...}

    public function remove_file() {...}

    public function append_cronjob() {...}

    public function remove_cronjob() {...}

    public function remove_crontab() {...}

    private function crontab_file_exists() {...}

    private function error_message() {...}

}

Here each function serves separate tasks

For instance, __construct() used to construct a one, while exec() responsible for execution of it.

Write_to_file() necessary for writing it to file, append_cronjob() append one in the list. Soon.

Let's look at each function one by one

  1. __construct()

 

function __construct($host=NULL, $port=NULL, $username=NULL, $password=NULL)

{

    $path_length     = strrpos(__FILE__, "/");     

    $this->path      = substr(__FILE__, 0, $path_length) . '/';

    $this->handle    = 'crontab.txt';       

    $this->cron_file = "{$this->path}{$this->handle}";

    try

    {

        if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) throw new Exception("Please specify the host, port, username and password!");

        $this->connection = @ssh2_connect($host, $port);

        if ( ! $this->connection) throw new Exception("The SSH2 connection could not be established.");

        $authentication = @ssh2_auth_password($this->connection, $username, $password);

        if ( ! $authentication) throw new Exception("Could not authenticate '{$username}' using password: '{$password}'.");

    }

    catch (Exception $e)

    {

        $this->error_message($e->getMessage());

    }

}

​​​​​​​2. exec()

public function exec()

{

    $argument_count = func_num_args();

    try

    {

        if ( ! $argument_count) throw new Exception("There is nothing to execute, no arguments specified.");

        $arguments = func_get_args();

        $command_string = ($argument_count > 1) ? implode(" && ", $arguments) : $arguments[0];

        $stream = @ssh2_exec($this->connection, $command_string);

        if ( ! $stream) throw new Exception("Unable to execute the specified commands: <br />{$command_string}");

    }

    catch

    {

        $this->error_message($e->getMessage());

    }

    return $this;

}

3. write_to_file()

public function write_to_file($path=NULL, $handle=NULL)

{

    if ( ! $this->crontab_file_exists())

    {  

        $this->handle = (is_null($handle)) ? $this->handle : $handle;

        $this->path   = (is_null($path))   ? $this->path   : $path;

        $this->cron_file = "{$this->path}{$this->handle}";

        $init_cron = "crontab -l > {$this->cron_file} && [ -f {$this->cron_file} ] || > {$this->cron_file}";

        $this->exec($init_cron);

    }

    return $this;

}

4. remove_file()

public function remove_file()

{

    if ($this->crontab_file_exists()) $this->exec("rm {$this->cron_file}");

    return $this;

}

5. append_cron_job()

public function append_cronjob($cron_jobs=NULL)

{

    if (is_null($cron_jobs)) $this->error_message("Nothing to append!  Please specify a cron job or an array of cron jobs.");

    $append_cronfile = "echo '";       

    $append_cronfile .= (is_array($cron_jobs)) ? implode("\n", $cron_jobs) : $cron_jobs;

    $append_cronfile .= "'  >> {$this->cron_file}";

    $install_cron = "crontab {$this->cron_file}";

    $this->write_to_file()->exec($append_cronfile, $install_cron)->remove_file();

    return $this;

}

6. remove cron jobs

public function remove_cronjob($cron_jobs=NULL)

{

    if (is_null($cron_jobs)) $this->error_message("Nothing to remove!  Please specify a cron job or an array of cron jobs.");

    $this->write_to_file();

    $cron_array = file($this->cron_file, FILE_IGNORE_NEW_LINES);

    if (empty($cron_array)) $this->error_message("Nothing to remove!  The cronTab is already empty.");

    $original_count = count($cron_array);

    if (is_array($cron_jobs))

    {

        foreach ($cron_jobs as $cron_regex) $cron_array = preg_grep($cron_regex, $cron_array, PREG_GREP_INVERT);

    }

    else

    {

        $cron_array = preg_grep($cron_jobs, $cron_array, PREG_GREP_INVERT);

    }  

    return ($original_count === count($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array);

}

Comments

Sign in to publish a comment

0 comments

Be the first to comment on this post.