Cron PHP: Run Tasks As Scheduled!
Cron PHP has to do with using the Linux system process cronTab to create a dynamic PHP class, which you can learn more about with this Linux course.
The cronTab facilitates repetitive task scheduling. When you create cron PHP using a secure connection, this gives you a way to manipulate the cronTab, which you can read more about in this PHP article.
Basically, Cron gives you the ability to run scheduled tasks in the background. Cron also helps in grabbing RSS feeds, analyzing performance, running tasks of clean-up, sending/fetching emails or backing up SQL databases, which you can learn more about in this SQL course.
Remember that cron jobs will each have 5 chronological columns, with each representing an operator with a full command path to execute:
Each of the columns has a specified relevance to the task schedule:
Days of the week represent week days from Sunday to Saturday using the numbers zero to six respectively.
Months represent a given year’s months, one to twelve in that order
Days represents a given month’s days, one to thirty-one in that order.
Hours represent a given day’s hours, zero to twenty-three in that order.
Minutes represent a given hour’s minutes, zero to fifty-nine in that order.
So if you wanted a task scheduled to run at eight thirty every Saturday morning you would write:
If you wanted to schedule tasks on the first day of each month at twelve in the morning, it would look like:
You can also use a few operators to customize the scheduled tasks even more:
- Asterisks are used to indicate every value/all
- Dashes are used for indicating ranges of values
- Commas are used for creating a comma-separated values list for any of the columns in cron.
By default, cronTabs send notifications through email when a task that has been scheduled gets done.
Managing Cron with PHP
You will need to execute commands in order to manage cronTab with PHP, which you can learn more about in this PHP 101 course. The good news is that there is a simple way to do this with PHP. You can begin by declaring 4 properties:
- $cron-File represents the name and full path of the cron temporary file.
- $handle represents the temporary cron file name.
- $path represents a file’s path.
- $connection represents your resource/connection.
In order to have access to the cronTab and execute commands, your class needs to authenticate and connect as an appropriate user. For this reason, you might want to establish a connection with SSH2 and get authenticated.
When authenticated connections are established, you will need a way of handling all the commands executed. Exec() can be the name of this method. In general, when you need to execute commands on a remote server, you can call this method from inside other class methods.
Naturally, you will need a method of removing and creating cron PHP jobs. To do this you can define methods with ‘remove_cronjob()’ and ‘append_cronjob()’ respectively.
So that you will have tangible access to your file, you will then need to write the cronTab to a file. Once you are finished with it, you will also need a method of deleting it. A method for handling a cronTab’s output to a file also needs to be handled as ‘write_to_files()’ and the file removal would be ‘remove_files()’
In cases where only the last or the only cron job has been removed, you will want to be able to remove the cronTab entirely instead of attempting to create a cronTab that turns out empty. To handle this, you can use the method ‘remove_crontab()’
For your class, you can then create 2 helper methods. The 1st method returns a Boolean value and simply checks for existing cron temporary files. The 2nd method is utilized for error message displays if there are occurrences of erros. These methods can be named ‘crontab_file_exists()’ and ‘error_message()’ respectively.
Creating New Jobs in Cron
Creating new cron jobs can be done by executing the ‘crontab’ command after adding new lines/jobs to the cron temporary file. The ‘crontab’ command installs all the jobs as the new cronTab. When this happens, one argument ‘$cron_jobs’ will be taken by ‘append_cronjob()’ which will either be an array of strings or a string that represents the jobs in cron to append.
This method can be started off by first making a determination of a NULL argument in ‘$cron-jobs.’ If so, you can use the method ‘error_message()’ to display an error message and halt any more executions to the user.
The new variable ‘$append-cronfile’ can then be defined as a string, with the ‘echo’ text followed by one single quote and a space at the ending. This string can be populated with various jobs of cron that you add as well as closing quotes. You can use the string concatenation operator (.=)to build this string.
Determine whether @cron_jobs are arrays or not using a ternary operator. If so, you can get add new lines to this array \n so that within the cron file each of the jobs is written on its own line. When the ‘$cron_job’ is not an array, you can concatenate this job on a string ‘$append_cron’ without any other extra processes. This way, you will have a string in correct format whether or not you are dealing with arrays.
By redirecting standard outputs once more into the file, the task can just be echoed into the cron file. Using the ‘.=’ you can begin appending the single closing quote to the Linux operator >> and the string command followed by the file name and full path of the cron file. Unlike the > operator which always gets a file overwritten, the >> appends output to the file end.
In other words, when this is the operator you use, you can be assured that you won’t be overwriting any cron jobs that already exist. Next, you can check to see if your code is written securely, which you can learn more about in this PHP Security course.
Top courses in PHP
PHP students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.