1. Code
  2. PHP

Managing Cron Jobs With PHP

Scroll to top

The crontab, or cron table, is a Linux system process/daemon that facilitates the scheduling of repetitive tasks, thereby easing our day-to-day routine. In this tutorial, we'll create a dynamic PHP class, which allows us to manipulate the crontab using a secure connection.

Background: An Overview of the Crontab

Having the ability to schedule tasks to run in the background is just great! Backing up an SQL database, fetching or sending emails, running clean-up tasks, analyzing performance, or even grabbing RSS feeds—cron jobs are fantastic!

Although the syntax of scheduling a new job may seem daunting at first glance, it's relatively simple to understand once you break it down. A cron job will always have five columns, each of which represents a chronological operator followed by the full path and command to execute:

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

Each of the chronological columns has a specific relevance to the schedule of the task. They are as follows:

  • Minutes represents the minutes of a given hour, 0-59 respectively.
  • Hours represents the hours of a given day, 0-23 respectively.
  • Days represents the days of a given month, 1-31 respectively.
  • Months represents the months of a given year, 1-12 respectively.
  • Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.
1
Minutes [0-59]
2
|	Hours [0-23]
3
|	|	Days [1-31]
4
|	|	|	Months [1-12]
5
|	|	|	|	Days of the Week [Numeric, 0-6]
6
|	|	|	|	|
7
*	*	*	*	* home/path/to/command/the_command.sh

So, for example, if you want to schedule a task for 12am on the first day of every month, it would look something like this:

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

On the other hand, if you want to schedule a task to run every Saturday at 8:30am, we'd write it as follows:

1
30 8 * * 6 home/path/to/command/the_command.sh

There are also a number of operators which can be used to customize the schedule even further:

  • Commas are used to create a comma-separated list of values for any of the cron columns.
  • Dashes are used to specify a range of values.
  • Asterisks are used to specify all or every value.

The crontab, by default, will send an email notification whenever a scheduled task is executed. In many circumstances, though, this just isn't needed. We can easily suppress this functionality by redirecting the standard output of this command to the black hole or /dev/null device. Essentially, this is a file that will discard everything written to it. Output redirection is done via the > operator. Let's take a look at how we can redirect standard output to the black hole using our sample cron job, which runs a scheduled task every Saturday at 8:30am:

1
30 8 * * 6 home/path/to/command/the_command.sh >/dev/null

Additionally, if we're redirecting the standard output to the null device, we'll probably want to redirect the standard errors as well. We can do this by simply redirecting standard errors to where the standard output is already redirected, the null device!

1
30 8 * * 6 home/path/to/command/the_command.sh >/dev/null 2>&1

Manage crontab With PHP: The Blueprint

In order to manage the crontab with PHP, we'll need the ability to execute commands on the remote server as the user whose crontab we're editing. Although you can use the SSH2 library provided by PHP, we're going to use the phpseclib library, which supports different protocols to communicate with remote servers.

How to Install and Use the phpseclib Library

The phpseclib library (PHP Secure Communications Library) is a PHP library which provides a set of methods and classes for secure communication protocols such as SSH, SFTP, and SSL/TLS. It allows us to incorporate secure communication capabilities into our applications without having to rely on external command-line tools or extensions.

If you're wondering why you would prefer to use the phpseclib over the core SSH2 functions provided by PHP, let's have a look at the benefits of the phpseclib library:

  • the SSH2 library provides limited functionality and may not support all SSH features
  • provides abstraction, which allows you to switch between different protocols easily
  • abstracts the complexities of the underlying protocols
  • easy to use and intuitive
  • it does not require any external dependencies or extensions
  • supports a wide range of secure communication protocols, including SSH, SFTP, SCP, FTPS, SSL/TLS, and more
  • well-documented, actively developed, and community support

As you can see, the phpseclib library can provide a more comprehensive and robust solution for secure communication needs.

Let's see how you can install it. You can install the phpseclib library with composer, as shown in the following snippet.

1
$composer install phpseclib/phpseclib

Once it's installed, you can start using the phpseclib library in your PHP code by including the autoloader script at the top of your PHP script, as shown in the following snippet.

1
<?php
2
require 'vendor/autoload.php';

Let's have a quick look at how you can do remote SSH2 login.

1
<?php
2
require 'vendor/autoload.php';
3
4
use phpseclib3\Net\SSH2;
5
6
$ssh = new SSH2('example.remote-server.com');
7
8
if (!$ssh->login('ssh-username', 'ssh-password')) {
9
    die('Login to remote server failed.');
10
}

So that's a brief introduction to the phpseclib library.

The Ssh2_crontab_manager Class Template

In this section, we'll discuss which methods we'll need to implement in our class.

Our class must be able to connect and authenticate, as an appropriate user, in order to execute commands and have access to the user's crontab. Thus, we'll establish an SSH2 connection and authenticate it within the constructor itself.

With an authenticated connection in place, we'll then need a method to handle the execution of the various commands we'll be running. We'll use the  exec() method provided by the phpseclib library. Generally, we'll call this method from within the other methods of our class when we need to execute a command on the remote server.

Next, we'll need the ability to write the crontab to a file, so that we have tangible access to it. We'll also need a way to delete this file when we're finished with it. We'll define the method which handles outputting the crontab to a file as write_to_file() and the method for removing this file as remove_file().

Of course, we'll also need a way to create and remove cron jobs. So we'll define append_cronjob() and remove_cronjob() methods respectively.

If we have removed the only or last cron job, we should have the option to remove the entire crontab instead of attempting to create an empty crontab. To handle this scenario, we can use the remove_crontab() method.

Lastly, we'll create two helper methods for our class. The first of these methods, which will return a boolean value, will simply check for the existence of the temporary cron file. The latter will be used for displaying error messages should an error occurs. We'll name these methods crontab_file_exists() and error_message() respectively.

Our barebones PHP class should look like this:

1
<?php
2
use phpseclib3\Net\SSH2;
3
4
Class Ssh2_crontab_manager {
5
    private $connection;
6
    private $path;
7
    private $handle;
8
    private $cron_file;
9
    
10
    public function __construct() {...}
11
    
12
    public function exec() {...}
13
    
14
    public function write_to_file() {...}
15
    
16
    public function remove_file() {...}
17
    
18
    public function append_cronjob() {...}
19
    
20
    public function remove_cronjob() {...}
21
    
22
    public function remove_crontab() {...}
23
    
24
    private function crontab_file_exists() {...}
25
    
26
    private function error_message() {...}
27
}
28
?>

Implement the Ssh2_crontab_manager Class

In this section, we'll implement various methods of our class.

The Constructor

The class constructor will primarily be responsible for establishing and authenticating the SSH2 connection.

Let's have a look at the __construct method.

1
public function __construct($host = null, $port = null, $username = null, $password = null)
2
{
3
    $path_length = strrpos(__FILE__, "/");
4
    $this->path = substr(__FILE__, 0, $path_length) . '/';
5
    $this->handle = 'crontab.txt';
6
    $this->cron_file = "{$this->path}{$this->handle}";
7
8
    try {
9
        if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) {
10
            throw new Exception("Please specify the host, port, username, and password!");
11
        }
12
13
        $this->connection = new SSH2($host, $port);
14
        if (!$this->connection->login($username, $password)) {
15
            throw new Exception("Could not authenticate '{$username}' using password: '{$password}'.");
16
        }
17
    } catch (Exception $e) {
18
        $this->error_message($e->getMessage());
19
    }
20
}

Firstly, it takes four arguments, each of which will have a default value of NULL:

  • $host: represents the IP address of the remote server we want to connect to.
  • $port: the port to be used for the SSH2 connection.
  • $username: represents the user's login name for the server.
  • $password: represents the user's password for the server.

Firstly, it calculates the path to the current file and sets it to the $this->path variable. It also sets the name of the cron file to be used in $this->handle and constructs the full path to the cron file in $this->cron_file.

Then, we check if any of the required parameters are missing, and if so, it throws an exception with an appropriate error message.

Next, it creates an instance of the SSH2 class by passing in the $host and $port values to establish an SSH connection.

Finally, it tries to authenticate using the provided $username and $password by calling the login() method of the SSH2 connection object. If the authentication is successful, the connection is established. If it fails, an exception is thrown.

The exec Method

The exec method is responsible for executing commands on the remote server. It's comparable to manually entering commands into a shell like, say, PuTTY. To allow for greater flexibility, we'll make this method public so that users can actually execute any other commands that they may need to run.

Let's have a look at the exec method.

1
public function exec()
2
{
3
    $argument_count = func_num_args();
4
    
5
    try {
6
        if (!$argument_count) {
7
            throw new Exception("There is nothing to execute, no arguments specified.");
8
        }
9
    
10
        $arguments = func_get_args();
11
        $command_string = ($argument_count > 1) ? implode(" && ", $arguments) : $arguments[0];
12
        $stream = $this->connection->exec($command_string);
13
    
14
        if (!$stream) {
15
            throw new Exception("Unable to execute the specified commands: <br />{$command_string}");
16
        }
17
    } catch (Exception $e) {
18
        $this->error_message($e->getMessage());
19
    }
20
    
21
    return $this;
22
}

Our exec() method uses the phpseclib library's exec method to execute commands.

The first thing we'll do in this method is define a variable representing a count of the total number of arguments passed. We'll use PHP's func_num_args() function to get this count. Next, within a try block, we'll check whether or not any arguments were passed to this method. If the argument count is 0, we'll throw a new exception with an appropriate message.

Next, using the func_get_args() function, we'll create an array of all the arguments which were passed to this method. Using a ternary operator, we'll then define a new variable, $command_string, as a single-line string representation of the actual Linux commands we'll be executing.

If we do have multiple commands to execute, we'll use PHP's implode() function to parse the arguments array into a string. We'll pass two arguments to implode(): the glue or separator, which is basically just a string that will be inserted between the array elements, and the array itself. We'll separate each element with the Linux operator &&, which allows us to execute multiple commands sequentially, on one line!

With our commands ready and parsed as a string, we can now try to use the exec() method from our SSH2 class to execute the command string over the established SSH connection. The returned value is stored in the $stream variable.

The write_to_file Method

The next method, write_to_file(), will be responsible for writing the existing crontab to a temporary file or creating a blank temporary file should no cron jobs exist. It will take two arguments:

  • the path of the temporary file we'll be creating
  • the name we should use when creating it

The write_to_file method should look like this.

1
public function write_to_file($path=NULL, $handle=NULL)
2
{
3
    if (! $this->crontab_file_exists())
4
    {	
5
    	$this->handle = (is_null($handle)) ? $this->handle : $handle;
6
    	$this->path   = (is_null($path))   ? $this->path   : $path;
7
    	$this->cron_file = "{$this->path}{$this->handle}";
8
    	$init_cron = "crontab -l > {$this->cron_file} && [ -f {$this->cron_file} ] || > {$this->cron_file}";
9
    
10
    	$this->exec($init_cron);
11
    }
12
    
13
    return $this;
14
}

Firstly, we check whether the cron file already exists by using the boolean crontab_file_exists() method, which we'll create shortly. If the file exists, there's no need to proceed. If it doesn't, we'll use a ternary operator to check the $path and $handle props to determine whether or not they're NULL. If either of them is NULL, we'll use the predefined fallbacks from our constructor to define them.

Then, we'll concatenate these properties together into a new property, which represents the full path and file name of the temporary cron file.

Next, we've used the Linux command crontab with the -l argument to display the users crontab as standard output. Then, using Linux's > operator, we'll redirect the standard output or STDOUT to our temporary cron file instead by concatenating $this->cron_file into the command string! Redirecting output to a file using the > operator will always create that file if it doesn't exist.

This works very well, but only if there are already jobs scheduled within the crontab. If there are no cron jobs, this file will never be created! Using the && operator, though, we can append additional commands/expressions to this string. So let's append a conditional expression to check if the cron file exists. If the file doesn't exist, this expression will evaluate to false. As such, we can then use the || or or operator after this conditional to create a new blank file if needed.

Commands placed after or will execute if the condition/conditions evaluate to false. Now, by using the > operator again, this time without preceding it with a specific command, we can create a new blank file. So essentially, this string of commands will output the crontab to a file and then check if that file exists, which would indicate that there are entries in the crontab, and then create a new blank file if it doesn't already exist.

Lastly, we've called the exec() method and passed the command string to it as the only argument. Then, in order to make this method chainable as well, we'll return $this.

The remove_file Method

Let's quickly have a look at the remove_file method.

1
public function remove_file()
2
{
3
    if ($this->crontab_file_exists()) $this->exec("rm {$this->cron_file}");
4
    
5
    return $this;
6
}

In this method, we've used our helper method, crontab_file_exists(), to check for the existence of the temporary cron file and then execute the Linux command rm to delete it if it does. As usual, we'll also return $this to maintain chainability.

The append_cronjob Method

The append_cronjob method creates new cron jobs by adding new jobs/lines to the temporary cron file and then executing the crontab command on that file, which will install all of those jobs as a new crontab. 

It looks like this:

1
public function append_cronjob($cron_jobs=NULL)
2
{
3
    if (is_null($cron_jobs)) $this->error_message("Nothing to append! Please specify a cron job or an array of cron jobs.");
4
    
5
    $append_cronfile = "echo '";		
6
    
7
    $append_cronfile .= (is_array($cron_jobs)) ? implode("\n", $cron_jobs) : $cron_jobs;
8
    
9
    $append_cronfile .= "' >> {$this->cron_file}";
10
    
11
    $install_cron = "crontab {$this->cron_file}";
12
    
13
    $this->write_to_file()->exec($append_cronfile, $install_cron)->remove_file();
14
    
15
    return $this;
16
}

The append_cronjob() method takes one argument, $cron_jobs, which will either be a string or an array of strings representing the cron jobs to append.

We'll start this method off by determining if the $cron_jobs argument is NULL. If it is, we'll call the error_message() method to halt any further execution and display an error message to the user.

Next, we've defined a new variable, $append_cronfile, as a string, with the text echo followed by a space and a single quote at the end. We'll be populating this string with the various cron jobs we're adding, as well as the closing quote, momentarily. We'll build this string using the string concatenation operator .=.

Next, using a ternary operator, we determine if $cron_jobs is an array or not. If it is, we'll implode that array with newline characters \n, so that each cron job is written on its own line within the cron file. If the $cron_jobs argument is not an array, we'll simply concatenate that job onto the $append_cron string without any special processing.

Essentially, we can just echo our task into the cron file by redirecting the standard output into the file again. So by using the string concatenation operator, we'll append the closing single quote to the command string, as well as the Linux operator >> followed by the full path and file name for the cron file. The >> operator, unlike the > operator which always overwrites a file, appends the output to the end of a file. So by using this operator, we won't overwrite any existing cron jobs.

Next, we've defined a variable as a string, with the command we're going to use to install the new cron file which we're about to create. This is as simple as calling the crontab command followed by the path and filename of the cron file.

Finally, before executing these commands via the exec() method, though, we'll first call the write_to_file() method to create the temporary cron file. Then, within a chain, we'll execute these commands and call the remove_file() method to delete the temporary file. Lastly, we'll return $this so that the append_cronjob() method is chainable.

The remove_cronjob Method

Now that we can create new cron jobs, it's only logical that we have the ability to remove them as well! And that's the purpose of the remove_cronjob method.

Let's have a look at it.

1
public function remove_cronjob($cron_jobs=NULL)
2
{
3
    if (is_null($cron_jobs)) $this->error_message("Nothing to remove! Please specify a cron job or an array of cron jobs.");
4
    
5
    $this->write_to_file();
6
    
7
    $cron_array = file($this->cron_file, FILE_IGNORE_NEW_LINES);
8
    
9
    if (empty($cron_array)) $this->error_message("Nothing to remove! The cronTab is already empty.");
10
    
11
    $original_count = count($cron_array);
12
    
13
    if (is_array($cron_jobs))
14
    {
15
    	foreach ($cron_jobs as $cron_regex) $cron_array = preg_grep($cron_regex, $cron_array, PREG_GREP_INVERT);
16
    }
17
    else
18
    {
19
    	$cron_array = preg_grep($cron_jobs, $cron_array, PREG_GREP_INVERT);
20
    }	
21
    
22
    return ($original_count === count($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array);
23
}

It takes a single argument, which will be a (simple) regular expression. It will be used to find matching jobs within the crontab and remove them accordingly.

With the cron file created, we'll now read it into an array using PHP's file() function. This function will parse a given file into an array, with each line as an array element. We've passed our cron file to this function as the first argument and then set a special flag, FILE_IGNORE_NEW_LINES, which will force file() to ignore all new lines. Thus, we have an array with only the cron jobs themselves. Should there be no cron jobs scheduled, this array will be empty. Subsequently, there will be no reason to continue. Thus, we've checked to see if the $cron_array is empty and halt execution if it is.

Now, we determine if the $cron_jobs argument is an array or not. If it is an array, we iterate through it with a foreach loop. Within that loop, we execute a function preg_grep(). This nifty function, not unlike preg_match(), will return an array of all the array elements that match the regular expression specified. In this case, however, we want the array elements that don't match. In other words, we need an array of all the cron jobs that we're going to keep so that we can initialize the crontab with just these jobs. As such, we'll set a special flag here, PREG_GREP_INVERT, which will cause preg_grep() to return an array of all the elements which don't match the regular expression. Thus, we'll have an array of all the cron jobs we want to keep.

If the $cron_jobs argument is not an array, we'll proceed in the same manner but without any iteration. Again, we'll redefine $cron_array as the resulting array from the preg_grep() function with the PREG_GREP_INVERT flag set.

With our $cron_array set, now we compare the current length of this array with its original length, which we cached in the variable $original_count. If the lengths are identical, we'll simply return the remove_file() method to delete the temporary cron file. If they don't match, we'll remove the existing crontab and then install the new one.

The remove_crontab Method

Removing the entire crontab is relatively easy to implement, as shown in the following snippet.

1
public function remove_crontab()
2
{
3
    $this->exec("crontab -r")->remove_file();
4
    
5
    return $this;
6
}

Other Helper Methods

With the brunt of our cron management class written, we'll now take a look at the two small but useful methods we've used throughout our class, crontab_file_exists() and error_message().

The crontab_file_exists Method

This method returns the result of PHP's file_exists() method, true or false, depending on whether or not the temporary cron file exists.

1
private function crontab_file_exists()
2
{
3
    return file_exists($this->cron_file);
4
}

The error_message Method

This method takes a single argument, a string, representing the error message we want to display. We'll then call PHP's die() method to halt execution and display this message. The string itself will be concatenated into a <pre> element with a simple style applied to it.

1
private function error_message($error)
2
{
3
    die("<pre style='color:#EE2711'>ERROR: {$error}</pre>");
4
}

The complete class looks like this:

1
<?php
2
use phpseclib3\Net\SSH2;
3
4
Class Ssh2_crontab_manager {
5
    private $connection;
6
    private $path;
7
    private $handle;
8
    private $cron_file;
9
    
10
    public function __construct($host = null, $port = null, $username = null, $password = null)
11
    {
12
        $path_length = strrpos(__FILE__, "/");
13
        $this->path = substr(__FILE__, 0, $path_length) . '/';
14
        $this->handle = 'crontab.txt';
15
        $this->cron_file = "{$this->path}{$this->handle}";
16
        
17
        try {
18
            if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) {
19
                throw new Exception("Please specify the host, port, username, and password!");
20
            }
21
            
22
            $this->connection = new SSH2($host, $port);
23
            if (!$this->connection->login($username, $password)) {
24
                throw new Exception("Could not authenticate '{$username}' using password: '{$password}'.");
25
            }
26
        } catch (Exception $e) {
27
            $this->error_message($e->getMessage());
28
        }
29
    }
30
    
31
    public function exec()
32
    {
33
        $argument_count = func_num_args();
34
        
35
        try {
36
            if (!$argument_count) {
37
                throw new Exception("There is nothing to execute, no arguments specified.");
38
            }
39
            
40
            $arguments = func_get_args();
41
            $command_string = ($argument_count > 1) ? implode(" && ", $arguments) : $arguments[0];
42
            $stream = $this->connection->exec($command_string);
43
            
44
            if (!$stream) {
45
                throw new Exception("Unable to execute the specified commands: <br />{$command_string}");
46
            }
47
        } catch (Exception $e) {
48
            $this->error_message($e->getMessage());
49
        }
50
        
51
        return $this;
52
    }
53
    
54
    public function write_to_file($path=NULL, $handle=NULL)
55
    {
56
        if (! $this->crontab_file_exists())
57
        {	
58
            $this->handle = (is_null($handle)) ? $this->handle : $handle;
59
            $this->path   = (is_null($path))   ? $this->path   : $path;
60
            $this->cron_file = "{$this->path}{$this->handle}";
61
            $init_cron = "crontab -l > {$this->cron_file} && [ -f {$this->cron_file} ] || > {$this->cron_file}";
62
            
63
            $this->exec($init_cron);
64
        }
65
        
66
        return $this;
67
    }
68
    
69
    public function remove_file()
70
    {
71
        if ($this->crontab_file_exists()) $this->exec("rm {$this->cron_file}");
72
        
73
        return $this;
74
    }
75
    
76
    public function append_cronjob($cron_jobs=NULL)
77
    {
78
        if (is_null($cron_jobs)) $this->error_message("Nothing to append! Please specify a cron job or an array of cron jobs.");
79
        
80
        $append_cronfile = "echo '";		
81
        
82
        $append_cronfile .= (is_array($cron_jobs)) ? implode("\n", $cron_jobs) : $cron_jobs;
83
        
84
        $append_cronfile .= "' >> {$this->cron_file}";
85
        
86
        $install_cron = "crontab {$this->cron_file}";
87
        
88
        $this->write_to_file()->exec($append_cronfile, $install_cron)->remove_file();
89
        
90
        return $this;
91
    }
92
    
93
    public function remove_cronjob($cron_jobs=NULL)
94
    {
95
        if (is_null($cron_jobs)) $this->error_message("Nothing to remove! Please specify a cron job or an array of cron jobs.");
96
        
97
        $this->write_to_file();
98
        
99
        $cron_array = file($this->cron_file, FILE_IGNORE_NEW_LINES);
100
        
101
        if (empty($cron_array)) $this->error_message("Nothing to remove! The cronTab is already empty.");
102
        
103
        $original_count = count($cron_array);
104
        
105
        if (is_array($cron_jobs))
106
        {
107
            foreach ($cron_jobs as $cron_regex) $cron_array = preg_grep($cron_regex, $cron_array, PREG_GREP_INVERT);
108
        }
109
        else
110
        {
111
            $cron_array = preg_grep($cron_jobs, $cron_array, PREG_GREP_INVERT);
112
        }	
113
        
114
        return ($original_count === count($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array);
115
    }
116
    
117
    public function remove_crontab()
118
    {
119
        $this->exec("crontab -r")->remove_file();
120
        
121
        return $this;
122
    }
123
    
124
    private function crontab_file_exists()
125
    {
126
        return file_exists($this->cron_file);
127
    }
128
    
129
    private function error_message($error)
130
    {
131
        die("<pre style='color:#EE2711'>ERROR: {$error}</pre>");
132
    }
133
}
134
?>

Putting It All Together

Now that we've completed our cron management class, let's take a look at a few examples of how to use it.

Instantiating the Class and Establishing an Authenticated Connection

Firstly, let's create a new instance of our class. Remember, we'll need to pass the IP address, port, username, and password to the class constructor.

1
<?php
2
require 'vendor/autoload.php';
3
include "./ssh2_crontab_manager.php";
4
5
$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');

Appending a Single Cron Job

With an authenticated connection in place, let's have a look at how we can create a new, single, cron job.

1
<?php
2
require 'vendor/autoload.php';
3
include "./ssh2_crontab_manager.php";
4
5
$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
6
$crontab->append_cronjob('30 8 * * 6 home/path/to/command/the_command.sh >/dev/null 2>&1');

Appending an Array of Cron Jobs

Appending multiple cron jobs is just as easy as appending a single cron job. We'll simply pass an array to the append_cronjob() method.

1
<?php
2
require 'vendor/autoload.php';
3
include "./ssh2_crontab_manager.php";
4
5
$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
6
7
$new_cronjobs = array(
8
	'0 0 1 * * home/path/to/command/the_command.sh',
9
	'30 8 * * 6 home/path/to/command/the_command.sh >/dev/null 2>&1'
10
);
11
12
$crontab->append_cronjob($new_cronjobs);

Removing a Single Cron Job

In a similar manner to how we created a single cron job, we'll now remove one. This time, however, we'll use a regular expression to find the appropriate task. This regex can be as simple or as complex as you need it to be. In fact, there are a number of ways to regex for the task you're looking for. For example, if the task you need to remove is unique in that the command being run is not used anywhere else in the crontab, you could simply specify the command name as your regex. Furthermore, if you wanted to remove all the tasks for a certain month, you could simply write a regular expression to find a match for all the jobs of a given month.

1
<?php
2
require 'vendor/autoload.php';
3
include "./ssh2_crontab_manager.php";
4
5
$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
6
$cron_regex = '/home\/path\/to\/command\/the_command\.sh\/';
7
$crontab->remove_cronjob($cron_regex);

Removing an Array of Cron Jobs

Removing multiple cronjobs is handled in the same manner as removing a single cronjob, with a single exception: we'll pass an array of cron job regular expressions to the remove_cronjob() method.

1
<?php
2
require 'vendor/autoload.php';
3
include "./ssh2_crontab_manager.php";
4
5
$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
6
7
$cron_regex = array(
8
	'/0 0 1 \* \*/',
9
	'/home\/path\/to\/command\/the_command\.sh\/'
10
);
11
12
$crontab->remove_cronjob($cron_regex);

Conclusion

That's all, folks! I hope you've enjoyed reading this article as much as I've enjoyed writing it and that you've gained new insights into the crontab and managing it with PHP. Thank you so much for reading.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.