Wednesday, November 29, 2023
HomeVideo EditingManaging Cron Jobs With PHP

Managing Cron Jobs With PHP


The cronTab, or “Cron Desk”, is a Linux system course of / daemon which facilitates the scheduling of repetitive duties thereby easing up our everyday routine.

On this tutorial, we’ll create a dynamic PHP class that, utilizing a safe connection, offers us with a way to govern the cronTab!

Premium Choices

You could find an enormous number of PHP scripts on Envato Market, a lot of which will help in conditions like this.

For instance, take a look at Net Cronjobs, a robust web-based device that permits you to handle all of your cron jobs in a single place.

Web CronjobsWeb CronjobsWeb Cronjobs
Net Cronjobs

Background – An Overview of the Crontab

Let’s face it, being able to schedule duties to run within the background is simply nice! From backing up an SQL database, fetching / sending emails to operating clear up duties, analyzing efficiency, and even grabbing RSS feeds, cron jobs are incredible!

Though the syntax of scheduling a brand new job could appear daunting at first look, it is truly comparatively easy to grasp when you break it down. A cron job will all the time have 5 columns every of which characterize a chronological ‘operator’ adopted by the total path and command to execute:

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

Every of the chronological columns has a selected relevance to the schedule of the duty. They’re 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 times of a given month, 1-31 respectively.
  • Months represents the months of a given 12 months, 1-12 respectively.
  • Day of the Week represents the day of the week, Sunday by way of 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
	*	*	*	*	* dwelling/path/to/command/the_command.sh

So, for instance, if one wished to schedule a activity for 12am on the primary day of each month it will look one thing like this:

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

If we wished to schedule a activity to run each Saturday at 8:30am we might write it as follows:

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

There are additionally quite a lot of operators which can be utilized to customise the schedule even additional:

  • Commas is used to create a comma separated record of values for any of the cron columns.
  • Dashes is used to specify a spread of values.
  • Asterisksis used to specify ‘all’ or ‘each’ worth.

The cronTab, by default, will ship an electronic mail notification each time a scheduled activity is executed.

The cronTab, by default, will ship an electronic mail notification each time a scheduled activity is executed. In lots of circumstances, although, this simply is not wanted. We will simply suppress this performance, although, by redirecting the usual output of this command to the ‘black gap’ or /dev/null gadget. Basically, this can be a file that may discard the whole lot written to it. Output redirection is finished by way of the > operator. Let’s check out how we will redirect normal output to the black gap utilizing our pattern cron job which runs a scheduled activity each Saturday at 8:30am:

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

Moreover, if we’re redirecting the usual output to a the null gadget, we’ll most likely need to redirect the usual errors as nicely. We will do that by merely redirecting normal errors to the place the usual output is already redirected, the null gadget!

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

Step 1 – The Blueprint

As a way to handle the cronTab with PHP, we’ll want the power to execute instructions, on the distant server, because the consumer whose cronTab we’re enhancing. Thankfully, PHP offers us with a easy means to do that by way of the SSH2 library. Chances are you’ll or might not have this library put in so when you do not, you may need to get it put in:

PHP libssh2 Set up / Configuration

We’ll begin our class off by declaring 4 properties, all of which will likely be non-public:

  • $connection represents our connection / useful resource.
  • $path will characterize the trail for that file.
  • $deal with will characterize the title of our short-term cron file.
  • $cron_file represents the total path and title of the short-term cron file.

Our class should be capable of join and authenticate, as an applicable consumer, as a way to execute instructions and have entry the that consumer’s cronTab. Thus, we’ll set up an SSH2 connection and authenticate it inside the constructor itself.

With an authenticated connection in place, we’ll then want a technique to deal with the execution of the assorted instructions we’ll be operating. We’ll title this methodology exec(). Usually, we’ll name this methodology from inside the different strategies of our class when we have to execute a command on the distant server.

Subsequent, we’ll want the power to write down the cronTab to a file in order that we’ve tangible entry to it. We’ll additionally want a approach to delete this file once we’re completed with it. Let’s outline the strategy that handles outputting the cronTab to a file as write_to_file() and the strategy for eradicating this file as remove_file().

After all, we’ll additionally want a approach to create and take away cron jobs. So we’ll outline an append_cronjob() and remove_cronjob() methodology, respectively.

Within the case that we have eliminated the one / final cronjob we’ll need the power to take away the complete cronTab relatively than attempting to create an empty cronTab. We’ll use the strategy remove_crontab() to deal with this.

Lastly, we’ll create two helper strategies for our class. The primary of those strategies, which is able to return a boolean worth, will merely examine for the existence of the short-term cron file. The latter will likely be used for displaying error messages ought to an error happen. We’ll title this strategies crontab_file_exists() and error_message(), respectively.

1
	<?php
2

3
	Class Ssh2_crontab_manager {
4

5
		non-public $connection;
6
		non-public $path;
7
		non-public $deal with;
8
		non-public $cron_file;
9

10
		operate __construct() {...}
11

12
		public operate exec() {...}
13

14
		public operate write_to_file() {...}
15

16
		public operate remove_file() {...}
17

18
		public operate append_cronjob() {...}
19

20
		public operate remove_cronjob() {...}
21

22
		public operate remove_crontab() {...}
23

24
		non-public operate crontab_file_exists() {...}
25

26
		non-public operate error_message() {...}
27

28
	}

Step 2 – The Constructor!

The category constructor will primarily be chargeable for establishing and authenticating the SSH2 connection. It would take 4 arguments, every of which could have a default worth of NULL:

  • $host: represents the ip deal with of the distant server we need to hook up with.
  • $port: is the port for use for the SSH2 connection.
  • $username: will characterize the consumer’s log in title for the server.
  • $password:represents the consumer’s password for the server.
1
	operate __construct($host=NULL, $port=NULL, $username=NULL, $password=NULL) {...}

Inside the constructor itself, the primary property we’ll outline is $this->path which is able to characterize a ‘default listing’ for our short-term cron recordsdata.

Ideally, we might merely use PHP’s magic fixed __DIR__ to outline this prop as the present working listing. There are, nevertheless, events the place this fixed might not be outlined. As such, we’ll examine to see if __DIR__ is outlined.

If it isn’t, we’ll need to get the present working listing manually. We’ll achieve this through the use of a mixture of the strrpos() and substr() features at the side of the __FILE__ fixed which represents the total path and title of the present file.

We’ll use strrpos(), which returns the place of the final prevalence of a substring, to seek out the place of the final ahead slash within the __FILE__ string. This worth, which we’ll retailer because the var $path_length, will give us the variety of characters as much as however not together with the final ahead slash.

The substr() operate will type of ‘splice’ a string in that it returns a selected portion of a string based mostly on the beginning place of the splice and the variety of characters we wish returned.

We’ll move three arguments to the substr() operate

  • the string we’re working with
  • the beginning location of the splice, on this case 0
  • the top location of the splice which is represented by the $path_length variable.

We’ll then concatenate a ahead slash to the top of this string which is able to give us the present working listing.

1
	operate __construct($host=NULL, $port=NULL, $username=NULL, $password=NULL)
2
	{
3
		$path_length = strrpos(__FILE__, "/");		
4
		$this->path  = substr(__FILE__, 0, $path_length) . '/';
5
	}

Now, we’ll outline a default filename for the short-term cron file as $this->deal with after which concatenate the trail and deal with props collectively as $this->cron_file. This prop will characterize the total default path and filename for the short-term cron file.

1
	operate __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->deal with    = 'crontab.txt';		
6
		$this->cron_file = "{$this->path}{$this->deal with}";
7
	}

With these properties outlined, we’ll now work on making a connection to the server and authenticating it. We’ll add some primary error dealing with to our class be wrapping the next code in a attempt / catch block. On this method, we will catch errors and throw exceptions in order to offer the consumer with very particular suggestions.

Inside the attempt block, we’ll first examine to see that all the arguments have been outlined through the use of the is_null() operate which is able to return true or false. If any of those arguments are NULL, we’ll throw a brand new exception with an applicable message.

1
	operate __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->deal with    = 'crontab.txt';		
6
		$this->cron_file = "{$this->path}{$this->deal with}";
7

8
		attempt
9
		 is_null($port) 
12
		catch
13
		{
14

15
		}
16
	}

Subsequent, we’ll outline $this->connection by passing the $host and $port arguments to the ssh2_connect() operate which is able to set up a distant connection and return that useful resource or FALSE if the connection fails.

Since we’re utilizing our personal error dealing with, we’ll additionally use the error management operator @ which is able to suppress any error messages for this operate. If the connection isn’t profitable, we’ll throw a brand new exception with an applicable message accordingly.

1
	operate __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->deal with    = 'crontab.txt';		
6
		$this->cron_file = "{$this->path}{$this->deal with}";
7

8
		attempt
9
		
15
		catch
16
		{
17

18
		}
19
	}

We’ll now try to authenticate / log in utilizing the ssh2_auth_password() operate passing within the useful resource returned from our connection in addition to the username and the password of the consumer we’re logging in. ssh2_auth_password() will return a boolean that represents the standing of the authentication utilizing which we will throw a brand new exception if the authentication fails.

1
	operate __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->deal with    = 'crontab.txt';		
6
		$this->cron_file = "{$this->path}{$this->deal with}";
7

8
		attempt
9
		{
10
			if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) throw new Exception("Please specify the host, port, username and password!");
11
			
12
			$this->connection = @ssh2_connect($host, $port);
13
			if ( ! $this->connection) throw new Exception("The SSH2 connection couldn't be established.");
14

15
			$authentication = @ssh2_auth_password($this->connection, $username, $password);
16
			if ( ! $authentication) throw new Exception("Couldn't authenticate '{$username}' utilizing password: '{$password}'.");
17
		}
18
		catch
19
		{
20

21
		}
22
	}

PHP will attempt to discover a matching catch block, for every exception which was thrown, after which create / move an exception object, which incorporates quite a lot of helpful properties, to this block.

So, within the catch block, we’ll use the exception object’s getMessage() methodology to entry and show the message outlined within the exception.

You may discover that we’ll be displaying the message by calling the error_message() methodology of our class. Though this methodology isn’t outlined but, it should merely show error messages in a tidy method.

1
	operate __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->deal with    = 'crontab.txt';		
6
		$this->cron_file = "{$this->path}{$this->deal with}";
7

8
		attempt
9
		{
10
			if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) throw new Exception("Please specify the host, port, username and password!");
11
			
12
			$this->connection = @ssh2_connect($host, $port);
13
			if ( ! $this->connection) throw new Exception("The SSH2 connection couldn't be established.");
14

15
			$authentication = @ssh2_auth_password($this->connection, $username, $password);
16
			if ( ! $authentication) throw new Exception("Couldn't authenticate '{$username}' utilizing password: '{$password}'.");
17
		}
18
		catch (Exception $e)
19
		{
20
			$this->error_message($e->getMessage());
21
		}
22
	}

Step 3 – Executing A number of Instructions

This methodology will likely be chargeable for executing instructions on the distant server. It is corresponding to manually coming into instructions right into a shell like, say, PuTTY. To permit for higher flexibility, we’ll make this methodology public in order that customers can truly execute every other instructions they could have to run. We’ll additionally enable for any variety of arguments as long as at the least one is specified. These arguments will characterize the instructions we need to run utilizing the ssh2_exec() operate.

So, the very first thing we’ll do on this methodology is outline a variable representing a rely of the overall variety of arguments handed. We’ll use PHP’s func_num_args() operate to get this rely.

1
	public operate exec()
2
	{
3
		$argument_count = func_num_args();
4
	}

Now, inside a attempt block, we’ll examine whether or not or not any arguments we’re handed to this methodology. If the argument rely is 0, we’ll throw a brand new exception with an applicable message.

1
	public operate exec()
2
	{
3
		$argument_count = func_num_args();
4

5
		attempt
6
		{
7
			if ( ! $argument_count) throw new Exception("There's nothing to execute, no arguments specified.");
8
		}
9
		catch
10
		{
11

12
		}
13
	}

Subsequent, utilizing the func_get_args() operate we’ll create an array of all of the arguments which had been handed to this methodology.

Utilizing a ternary operator, we’ll then outline a brand new variable, $command_string, as a single line string illustration of the particular Linux instructions we’ll be executing.

If we do have a number of instructions to execute, we’ll use PHP’s implode() operate to parse the arguments array right into a string. We’ll move two arguments to implode(), the glue, or separator, which is principally only a string that will likely be inserted between the array components, and the array itself. We’ll separate every ingredient with the Linux operator, && which is able to enable us to execute a number of instructions, sequentially, on one line!

Conversely, if there is just one command, we’ll outline the command string as $arguments[0] which represents the primary and solely argument / command.

1
	public operate exec()
2
	{
3
		$argument_count = func_num_args();
4

5
		attempt
6
		{
7
			if ( ! $argument_count) throw new Exception("There's nothing to execute, no arguments specified.");
8

9
			$arguments = func_get_args();
10

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

13
		}
14
		catch
15
		{
16

17
		}
18
	}

With our instructions prepared and parsed as a string, we will now attempt to execute them utilizing the ssh2_exec() operate. We’ll move the connection hyperlink id, $this->connection, in addition to our $command_string to this operate which is able to return a stream on success or false on failure.

Streams are outlined as a useful resource object which reveals streamable conduct… which might be learn from or written to in a linear trend.

We’ll use the error management operator @ right here, once more, to suppress any error messages as we’ll be throwing our personal exception, with an applicable message, ought to an error happen.

1
	public operate exec()
2
	{
3
		$argument_count = func_num_args();
4

5
		attempt
6
		{
7
			if ( ! $argument_count) throw new Exception("There's nothing to execute, no arguments specified.");
8

9
			$arguments = func_get_args();
10

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

13
			$stream = @ssh2_exec($this->connection, $command_string);
14
			if ( ! $stream) throw new Exception("Unable to execute the desired instructions: <br />{$command_string}");
15

16
		}
17
		catch
18
		{
19

20
		}
21
	}

That is it for the attempt block! Inside the catch block, we’ll merely name the error_message() methodology as a way to show any error messages to our consumer. With the attempt to catch blocks now full, we’ll return $this on the finish of the exec() methodology which is able to make this methodology chainable!

1
	public operate exec()
2
	{
3
		$argument_count = func_num_args();
4

5
		attempt
6
		{
7
			if ( ! $argument_count) throw new Exception("There's nothing to execute, no arguments specified.");
8

9
			$arguments = func_get_args();
10

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

13
			$stream = @ssh2_exec($this->connection, $command_string);
14
			if ( ! $stream) throw new Exception("Unable to execute the desired instructions: <br />{$command_string}");
15

16
		}
17
		catch
18
		{
19
			$this->error_message($e->getMessage());
20
		}
21

22
		return $this;
23
	}

Step 4 – Writing the CronTab to a File

The following methodology, write_to_file(), will likely be chargeable for writing the present cronTab to a short lived file or making a clean temp. file ought to no cron jobs exist. It would take two arguments

  • the trail for the short-term file we’ll be creating
  • the title we must always use when creating it.

Persevering with with the logic of our constructor and exec strategies, we’ll set default values for these arguments as NULL.

1
	public operate write_to_file($path=NULL, $deal with=NULL)
2
	{
3

4
	}

The very first thing we’ll do right here is examine to see if the cron file already exists through the use of the boolean crontab_file_exists() methodology, which we’ll create shortly. If the file does exist, there is no have to proceed. If it does not, we’ll use a ternary operator to examine the $path and $deal with props to find out whether or not or not they’re NULL. If both of them are NULL, we’ll use the predefined fallbacks from our constructor to outline them.

Then, we’ll concatenate these properties collectively into a brand new property which is able to characterize the total path and file title for the short-term cron file.

1
	public operate write_to_file($path=NULL, $deal with=NULL)
2
	{
3
		if ( ! $this->crontab_file_exists())
4
		{		
5
			$this->deal with = (is_null($deal with)) ? $this->deal with : $deal with;
6
			$this->path   = (is_null($path))   ? $this->path   : $path;
7

8
			$this->cron_file = "{$this->path}{$this->deal with}";
9
		}
10
	}

Subsequent, we’ll use the Linux command crontab, with the -l argument set, to show the customers cronTab as normal output. Then, utilizing Linux’s > operator, we’ll redirect normal output, or STDOUT, to our short-term cron file as an alternative by concatenating $this->cron_file into the command string! Redirecting output to a file, utilizing the > operator, will all the time create that file if it does not exist.

1
	public operate write_to_file($path=NULL, $deal with=NULL)
2
	{
3
		if ( ! $this->crontab_file_exists())
4
		{	
5
			$this->deal with = (is_null($deal with)) ? $this->deal with : $deal with;
6
			$this->path   = (is_null($path))   ? $this->path   : $path;
7

8
			$this->cron_file = "{$this->path}{$this->deal with}";
9

10
			$init_cron = "crontab -l > {$this->cron_file}";
11
		}
12
	}

This works very nicely however provided that there are already jobs scheduled inside the cronTab. If there are not any cron jobs, nevertheless, this file won’t ever be created! Utilizing the && operator although, we will append further instructions / expressions to this string. So, let’s append a conditional expression to examine that the cron file exists. If the file does not exist, this expression will consider to false. As such, we will then use the || or “or” operator after this conditional to create a brand new clean file if wanted!

Instructions positioned after “or” will execute if the situation / circumstances consider to false. Now, through the use of the > operator once more, this time with out previous it by a selected command, we will create a brand new clean file! So, primarily, this string of instructions will output the cronTab to a file, then examine if that file exists, which might point out that there are entries within the cronTab after which create a brand new clean file if it does not exist already!

1
	public operate write_to_file($path=NULL, $deal with=NULL)
2
	{
3
		if ( ! $this->crontab_file_exists())
4
		{	
5
			$this->deal with = (is_null($deal with)) ? $this->deal with : $deal with;
6
			$this->path   = (is_null($path))   ? $this->path   : $path;
7

8
			$this->cron_file = "{$this->path}{$this->deal with}";
9

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

Lastly, we’ll name the exec() methodology and move the command string to it as the one argument. Then, as a way to make this methodology chainable as nicely, we’ll return $this.

1
	public operate write_to_file($path=NULL, $deal with=NULL)
2
	{
3
		if ( ! $this->crontab_file_exists())
4
		{	
5
			$this->deal with = (is_null($deal with)) ? $this->deal with : $deal with;
6
			$this->path   = (is_null($path))   ? $this->path   : $path;
7

8
			$this->cron_file = "{$this->path}{$this->deal with}";
9

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

12
			$this->exec($init_cron);
13
		}
14

15
		return $this;
16
	}

Step 5 – Eradicating the Short-term Cron File

This methodology, remove_file() is as simple as simple may very well be! We’ll use our helper methodology, crontab_file_exists(), to examine for the existence of the short-term cron file after which execute the Linux command rm to delete it if it does. As traditional, we’ll additionally return $this as a way to preserve chainability.

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

5
		return $this;
6
	}

Step 6 – Creating New Cron Jobs

This methodology will create new cron jobs by means of including new jobs / strains to the short-term cron file after which executing the crontab command on that file which is able to set up all of these jobs as a brand new cronTab. As such, append_cronjob() will take one argument, $cron_jobs, which is able to both be a string or an array of strings representing the cron jobs to append.

We’ll begin this methodology off by figuring out if the $cron_jobs argument is NULL. Whether it is, we’ll name the error_message() methodology as a way to halt any additional execution and show an error message to the consumer.

1
	public operate 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
	}

Basically, we will simply echo our activity into the cron file by redirecting normal output into the file once more.

Subsequent, we’ll outline a brand new variable, $append_cronfile, as a string, with the textual content “echo” adopted by an area and one single quote on the finish. We’ll be populating this string with the assorted cron jobs we’re including in addition to the closing quote, momentarily. We’ll be constructing this string utilizing the string concatenation operator .=.

Utilizing a ternary operator, we’ll decide if $cron_jobs is an array or not. Whether it is, we’ll implode that array with new strains, n, so that every cron job is written on it is personal line inside the cron file. If the $cron_jobs argument isn’t an array, we’ll merely concatenate that job onto the $append_cron string with none particular processing. On this method, we’ll have a correctly formatted string no matter whether or not or not we’re working with an array.

Basically, we will simply echo our activity into the cron file by redirecting normal output into the file once more. So, utilizing the string concatenation operator, we’ll append the closing single quote to the command string in addition to the Linux operator >> adopted by the total path and file title for the cron file. The >> operator, in contrast to the > operator which all the time overwrites a file, appends output to the top of a file. So through the use of this operator, we cannot overwrite any present cron jobs.

1
	public operate 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
	}

We’ll now outline a variable, as a string, with the command we’ll use to put in the brand new cron file which we’re about to create! This is so simple as calling the crontab command adopted by the trail and filename of the the cron file.

Earlier than executing these instructions by way of the exec() methodology, although, we’ll first name the write_to_file() methodology as a way to create the short-term cron file. Then, inside a series, we’ll execute these instructions and name the remove_file() methodology to delete the short-term file. Lastly, we’ll return $this in order that the append_cronjob() methodology is chainable.

1
	public operate 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
	}

Step 7 – Eradicating Current Cron Jobs

Now that we will create new cron jobs, it is solely logical that we’ve the power to take away them as nicely! The remove_cronjob() methodology will take one argument which will likely be a (easy) common expression. This regEx will likely be used to seek out matching jobs inside the cronTab and take away them accordingly. As with the append_cronjob() methodology, the very first thing we’ll do is examine to see if the $cron_jobs argument is NULL and halt execution whether it is. If not, we’ll name the create_file() methodology so as write the cron tab to a file.

1
	public operate remove_cronjob($cron_jobs=NULL)
2
	{
3
		if (is_null($cron_jobs)) $this->error_message("Nothing to take away!  Please specify a cron job or an array of cron jobs.");
4
		
5
		$this->write_to_file();
6

7
	}

With the cron file created, we’ll now learn it into an array utilizing PHP’s file() operate. This operate will parse a given file into array with every line as an array ingredient. We’ll move our cron file to this operate as the primary argument after which set a particular flag, FILE_IGNORE_NEW_LINES, which is able to drive file() to disregard all new strains. Thus, we’ll have an array with solely the cron jobs themselves!

Ought to there be no cron jobs scheduled, this array will likely be empty. Subsequently, there will likely be no motive to proceed. Thus, we’ll examine to see if the $cron_array is empty and halt execution whether it is.

If the cronTab isn’t empty, we’ll then rely the weather within the $cron_array utilizing PHP’s rely() operate. We’ll retailer this worth as $original_count. We’ll use it, shortly, to find out if we have eliminated any cron jobs from the $cron_array.

1
	public operate remove_cronjob($cron_jobs=NULL)
2
	{
3
		if (is_null($cron_jobs)) $this->error_message("Nothing to take away!  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 take away!  The cronTab is already empty.");
10
		
11
		$original_count = rely($cron_array);
12

13
	}

Now, we’ll decide if the $cron_jobs argument is an array or not. Whether it is an array, we’ll iterate by way of it with a foreach loop. Inside that loop we’ll solely execute one operate, preg_grep(). This nifty operate, not in contrast to preg_match(), will return an array of all of the array components that match the common expression specified. On this case, nevertheless, we wish the array components that do not match. In different phrases, we want an array of all of the cron jobs that we’ll maintain in order that we will initialize the cronTab with simply these jobs. As such, we’ll set a particular flag right here, PREG_GREP_INVERT, which is able to trigger preg_grep() to return an array of all the weather which do not match the common expression. Thus, we’ll have an array of all of the cron jobs we need to maintain!

1
	public operate remove_cronjob($cron_jobs=NULL)
2
	{
3
		if (is_null($cron_jobs)) $this->error_message("Nothing to take away!  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 take away!  The cronTab is already empty.");
10
		
11
		$original_count = rely($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

20
		}	
21
	}

If the $cron_jobs argument isn’t an array, we’ll proceed in a lot the identical method however with none iteration. Once more, we’ll redefine $cron_array because the ensuing array from preg_grep() operate with the PREG_GREP_INVERT flag set.

1
	public operate remove_cronjob($cron_jobs=NULL)
2
	{
3
		if (is_null($cron_jobs)) $this->error_message("Nothing to take away!  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 take away!  The cronTab is already empty.");
10
		
11
		$original_count = rely($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
	}

With our $cron_array set, now, we’ll examine the present size of this array with it is unique size which we cached within the variable $original_count. If the lengths are an identical, we’ll merely return the remove_file() methodology to delete the short-term cron file. If they do not match, we’ll take away the present cronTab after which set up the brand new one!

The remove_file(), remove_crontab() and append_cronjob() strategies all return $this so by returning these strategies we’re nonetheless preserving this strategies chainability.

1
	public operate remove_cronjob($cron_jobs=NULL)
2
	{
3
		if (is_null($cron_jobs)) $this->error_message("Nothing to take away!  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 take away!  The cronTab is already empty.");
10
		
11
		$original_count = rely($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 === rely($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array);
23
	}

Step 8 – Eradicating the Complete Crontab

Eradicating the complete cronTab is comparatively easy to do. Basically, we’ll simply execute the crontab command with the -r flag set which removes the complete cronTab for a given consumer. Because the crontab has been eliminated we’d as nicely take away the short-term cron file as nicely, ought to it exist. Then we’ll return $this as a way to protect chainability.

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

Step 9 – A Few Useful Strategies

With the brunt of our cron administration class written, we’ll now check out the 2 small however helpful strategies we have used all through our class, crontab_file_exists() and error_message().

  • $this->crontab_file_exists()

    This methodology will merely return the results of PHP’s file_exists() methodology, true or false, relying on whether or not or not the short-term cron file exists.

1
	non-public operate crontab_file_exists()
2
	{
3
		return file_exists($this->cron_file);
4
	}

  • $this->error_message($error)

    This methodology will take one argument, a string, representing the error message we need to show. We’ll then name PHP’s die() methodology as a way to halt execution and show this message. The string it self, will likely be concatenated right into a <pre> ingredient with some easy fashion utilized to it.

1
	non-public operate error_message($error)
2
	{
3
		die("<pre fashion="coloration:#EE2711">ERROR: {$error}</pre>");
4
	}

Step 10 – Placing all of it collectively!

Now that we have accomplished our cron administration class, let’s check out a number of examples of the right way to use it!

  • Instantiating the category and establishing an authenticated connection:

    First, let’s create a brand new occasion of our class. Bear in mind, we’ll have to move the ip deal with, port, username and password to the category constructor.

1
		$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 take a look at how we will create a brand new, single, cron job.

1
		$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
2
		$crontab->append_cronjob('30 8 * * 6 dwelling/path/to/command/the_command.sh >/dev/null 2>&1');
1
		$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
2
		
3
		$new_cronjobs = array(
4
			'0 0 1 * * dwelling/path/to/command/the_command.sh',
5
			'30 8 * * 6 dwelling/path/to/command/the_command.sh >/dev/null 2>&1'
6
		);
7
		
8
		$crontab->append_cronjob($new_cronjobs);

  • Eradicating a single cron job:

    In like method to how we created a single cron job, we’ll now take away one. This time, nevertheless, we’ll use a daily expression to seek out the suitable activity. This regEx might be as easy or as advanced as you want it to be. In actual fact, there are a selection of how to regex for the duty you are searching for. For instance, if the duty it’s essential take away is exclusive in that the command being run isn’t used anyplace else within the cronTab, you possibly can easy specify the command title as you are regEx. Moreover, when you wished to take away all of the duties for a sure month, you possibly can merely write a daily expression to discover a match for all the roles of a given month!

1
		$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
2
		
3
		$cron_regex = '/dwelling/path/to/command/the_command.sh/';
4
		
5
		$crontab->remove_cronjob($cron_regex);
1
		$crontab = new Ssh2_crontab_manager('11.11.111.111', '22', 'my_username', 'my_password');
2
		
3
		$cron_regex = array(
4
			'/0 0 1 * */',
5
			'/dwelling/path/to/command/the_command.sh/'
6
		);
7
		
8
		$crontab->remove_cronjob($cron_regex);

Conclusion

That is all of us! I hope you have loved studying this text as a lot as I’ve loved writing it and that you have gained new insights into the cronTab and managing it with PHP. Thanks a lot for studying!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments