How to run Cron Job every 5 seconds using PHP

Hello, artisans welcome to another article. Recently I have developed an email autoresponder application for email marketers and CPA Marketers Strom Email Autoresponder is the name of software. This software handles clients emails and sends them responses and follow-ups automatically. So it requires a schedule manager to read emails from inbox, send them responses and follow-ups. So that I have to use Cron Job a schedule manager to manage automation. I could use cron jobs from a cPanel but the cP supports minimum 1-minute cron from VPS Server. That's why the server was working slowly. Then I thought to upgrade this system and make it fast and I made a decision to execute cron every 5 seconds and automation this system from the software.


I have developed the software using PHP so that I need to execute cron using PHP. I have created this using php like using the code which is provided bellow-


$output = $command = shell_exec('crontab -l');
$command_line = "* * * * * ( sleep 5 ; php ".getcwd()."/file.php request=1) >/dev/null 2>&1 \n";
if(substr_count($output,$command_line)==0){	$command.= $command_line;
}
file_put_contents('./crontab.txt', $command);
echo exec('crontab ./crontab.txt');

Now I am going to explain this. By using shell_exec('crontab -l'); $output & $command variable I got the existing cron jobs from the server. Then I wrote command what I actually wanted to run by the crontab. * * * * * means the cron will run in every second then I took a round bracket to write my command into this. I use the command sleep 5; for run the cron every 5 seconds. then I wrote rest of command and use \n end of the line for linebreak. I must put the whole command into a double quotation. Otherwise, linebreak will not work. Then I used file_put_content('./crontab.txt',$command); to write the cron command into crontab.txt file. Then finally I executed crontab by exec() command. 


Cheers! our cronjob is successfully executed using PHP. If you want to run this you must have to permission to execute shell_exec() & exec () command for your cPanel user. I hope you understand this article. If you have any question you can ask me. If you like this article then don't hesitate to share this article because of sharing knowledge increase knowledge.


Happy Programming!!

Sajjad Hossain
Hi, I'm Sajjad Hossain, a PHP Developer working on PHP Development since 2012. If you have a project that you want to start you can contact me. I'm currently available for freelance work. Ping me on Facebook, WhatsApp or Skype.

We use cookies on our website. To find out more about how and why they are used or opt-out, please read our Cookie Policy. By choosing "I Accept", you consent to our use of cookies. Cookie Policy
Top