Php Script for Cron Job
PHP Script for Cron Job is a simple cron job manager script using PHP and MySQL. It works in all PHP enabled servers, even localhost. Cron Job is an important task that keeps your server’s performance. This is an easy tool to help you manage your cron jobs. I have used php mail() function to notify you when errors appeared. The cron job runs daily (a day job), weekly or monthly by default setting from config file.
Php Script for Cron Job is a time management script for use in banks, web hosting companies, internet radio stations, and more. Use the admin panel to switch from hourly backup to 30 minutes or 15 minutes, or to enable the scheduler for all days of the week. It comes with a core dump feature in the event of an uncaught exception or php crash so that all information is preserved.
Running PHP scripts from cron jobs
A common method for running PHP scripts from a cron job is to use a command-line program such as curl or wget. For example, the cron job runs a command similar to the following command:
curl http://example.com/script.php
In this command, curl retrieves the web page, which then runs the PHP script.
However, there is a better way to run PHP scripts on your web site from cron jobs. You can run the script directly by using the PHP command-line interpreter. This method is just as effective, and usually faster. The following command shows how to run a script using the PHP command-line interpreter:
php -q ${HOME}/public_html/script.php
In this example, the PHP command-line interpreter runs the script.php file in the user’s public_html directory. The -q option enables quiet mode, which prevents HTTP headers from being displayed.
Depending on the code in your PHP script, it may only run correctly when called from a specific directory. For example, if the script uses relative paths to include files, it will only run if it is called from the correct directory. The following command shows how to call a PHP script from a specific directory:
cd ${HOME}/public_html/; php -q script.php
If your script requires special configuration options, you can use a custom php.ini file. The -c option allows you to call a PHP script using a custom php.ini file:
php -c ${HOME}/php.ini ${HOME}/public_html/script.php
Cron Jobs with PHP and other File Type
PHP
Command to run a PHP5 cron job:
php /home/username/public_html/cron.php
Optional flags are sometimes required for a PHP cron job:
php -q /home/username/public_html/cron.php
Command to use a specific php.ini file:
php -c /home/username/public_html/php.ini /home/username/public_html/myscript.php
Command to GET a remote file:
/usr/bin/GET http://www.example.com/file.php
Perl
Command to run a CGI cron job:
perl /home/username/public_html/cgi-bin/file.pl
SSH
Command to run a shell script cron job:
/bin/sh /home/username/public_html/file.sh
MySQL
It is good practice to not type your password out in the following commands but to use the -p flag alone and have the system prompt you for the password. This is why your password stays secure and is never on the server as plain text.
Command to import a database:
mysql -u mysql_user -ppassword database_name < backup.sql
Command to export a database:
mysqldump -u mysql_user -ppassword database_name > backup.sql
Configure Corn Task
In the following example, the crontab command shown below will activate the cron tasks automatically every five minutes:
*/5 * * * * /usr/bin/php /opt/test.php
In the above sample, the */5 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every “five” minute. The other figures represent, respectively, hour, day, month and day of the week.
* is a wildcard, meaning “every time”.
Find PHP Library
Type the below command to find the php library.
# whereis php
You will get some output like below:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
Cronjob Entry
Now type the below command to scheduled task and set cron like below.
# crontab -e */5 * * * * /usr/bin/php /opt/test.php
Now type wq! to save it.
How to set the cron job to run a PHP script in cPanel?
- Login to cPanel.
- Go to cPanel >> Home >> Advanced >> Cron Jobs.
Set a cron email:
- In the Email text box, enter the email address on which you wish to receive the cron notifications. Click on Update Email button.
Disable email notifications:
To disable email notifications for all cron jobs, remove the email address. If you do not want an Email notification for the Cron, you should add /dev/null 2>&1 in the command field. It will send the output to NULL.
Creating a PHP Script that Runs Tasks After 5 Seconds
In this step, you’ll create a script that uses a combination of the PHP while(...){...}
loop and sleep
functions to run tasks after every 5 seconds.
Open a new /var/www/html/tasks.php
file in the root directory of your web server using nano:
sudo nano /var/www/html/tasks.php
Copy
Next, create a new try {
block after a <?php
tag and declare the database variables that you created in Step 1. Remember to replace EXAMPLE_PASSWORD
with the actual password for your database user:/var/www/html/tasks.php
<?php
try {
$db_name = 'cron_jobs';
$db_user = 'cron_jobs_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
Copy
Next, declare a new PDO (PHP Data Object) class and set the attribute ERRMODE_EXCEPTION
to catch any PDO errors. Also, switch ATTR_EMULATE_PREPARES
to false
to let the native MySQL database engine handle emulation. Prepared statements allow you to send the SQL queries and data separately to enhance security and reduce chances of an SQL injection attack:/var/www/html/tasks.php
$pdo = new PDO('mysql:host=' . $db_host . '; dbname=' . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Copy
Then, create a new variable named $loop_expiry_time
and set it to the current time plus 60 seconds. Then open a new PHP while(time() < $loop_expiry_time) {
statement. The idea here is to create a loop that runs until the current time (time()
) matches the variable $loop_expiry_time
:/var/www/html/tasks.php
$loop_expiry_time = time() + 60;
while (time() < $loop_expiry_time) {
Copy
Next, declare a prepared SQL statement that retrieves unprocessed jobs from the tasks
table:/var/www/html/tasks.php
$data = [];
$sql = "select
task_id
from tasks
where is_processed = :is_processed
";
Copy
Execute the SQL command and fetch all rows from the tasks
table that have the column is_processed
set to N
. This means the rows are not processed:/var/www/html/tasks.php
$data['is_processed'] = 'N';
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
Copy
Next, loop through the retrieved rows using a PHP while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {...}
statement and create another SQL statement. This time around, the SQL command updates the is_processed
and completed_at
columns for each task processed. This ensures that you don’t process tasks more than one time:/var/www/html/tasks.php
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data_update = [];
$sql_update = "update tasks set
is_processed = :is_processed,
completed_at = :completed_at
where task_id = :task_id
";
$data_update = [
'is_processed' => 'Y',
'completed_at' => date("Y-m-d H:i:s"),
'task_id' => $row['task_id']
];
$stmt = $pdo->prepare($sql_update);
$stmt->execute($data_update);
}
Copy
Note: If you have a large queue to be processed (for example, 100,000 records per second), you might consider queueing jobs in a Redis Server since it is faster than MySQL when it comes to implementing the job-queue model. Nevertheless, this guide will process a smaller dataset.
Before you close the first PHP while (time() < $loop_expiry_time) {
statement, include a sleep(5);
statement to pause the jobs execution for 5 seconds and free up your server resources.
You may change the 5 seconds period depending on your business logic and how fast you want tasks to execute. For instance, if you would like the tasks to be processed 3 times in a minute, set this value to 20 seconds.
Remember to catch
any PDO error messages inside a } catch (PDOException $ex) { echo $ex->getMessage(); }
block:/var/www/html/tasks.php
sleep(5);
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
Copy
Your complete tasks.php
file will be as follows:/var/www/html/tasks.php
<?php
try {
$db_name = 'cron_jobs';
$db_user = 'cron_jobs_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$pdo = new PDO('mysql:host=' . $db_host . '; dbname=' . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$loop_expiry_time = time() + 60;
while (time() < $loop_expiry_time) {
$data = [];
$sql = "select
task_id
from tasks
where is_processed = :is_processed
";
$data['is_processed'] = 'N';
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data_update = [];
$sql_update = "update tasks set
is_processed = :is_processed,
completed_at = :completed_at
where task_id = :task_id
";
$data_update = [
'is_processed' => 'Y',
'completed_at' => date("Y-m-d H:i:s"),
'task_id' => $row['task_id']
];
$stmt = $pdo->prepare($sql_update);
$stmt->execute($data_update);
}
sleep(5);
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
Copy
Save the file by pressing CTRL
+ X
, Y
then ENTER
.
Once you’ve completed coding the logic in the /var/www/html/tasks.php
file, you’ll schedule the crontab daemon to execute the file after every 1 minute in the next step.
Conclusion
This Script is for those who want to create a cron job in php rather than any other server side scripting Languages .You can create a cronjob from your PHP script…