How to run PHP cron tasks without cron available
In most cases hosting panels has CRON jobs available, so using cron is not an issue. Just sometimes you do not want to bother with it because of many reasons like no cpanel password, makes your script installation process complicated, or even cron is simply not available at all.
In this case I found interesting technique how to overcome this.
The idea is simple and is borrowed from official documentation comments. In PHP it is possible to sent browser output and continue to execute other PHP code.
This means that on each page request, PHP generates full HTML, sends to the user and closes the connection. User is happy to view the page, however on the server PHP script may execute useful stuff.
Code looks like this:
ob_start(); // Generage HTML page here generate_full_html_page(); // All magic goes here $output = ob_get_clean(); ignore_user_abort(true); set_time_limit(0); header("Connection: close"); header("Content-Length: ".strlen($output)); header("Content-Encoding: none"); echo $output.str_repeat(' ', 10000) ."\n\n\n"; flush(); // Now page is sent and it safe to do all needed stuff here cron_task1(); cron_task2(); |
If you need to run CRON jobs continuously and not to depend on the user visits, you may initiate a SELF request to the same page using CURL after all tasks are done.
Based on this technique very easy to make a full CRON class which will handle all the dirty job, may be in future )
English
Русский
January 11th, 2012 - 18:09
You can also use a remote server cron job.
July 28th, 2012 - 19:21
Is this really going to work? I mean what if the user navigates away from the page?
Don’t we have to use the following as well?
ignore_user_abort(true);
set_time_limit(0);
ini_set(‘max_execution_time’, 0);
Will definitely try your approach.
July 28th, 2012 - 19:22
Scratch that I didn’t notice you used them.
July 30th, 2012 - 11:10
I used that code in one of my project and it worked great!