4Jan/125

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 )

Did you find this post useful? Support the the author ($10)
My Google Profile+
Comments (5) Trackbacks (1)
  1. You can also use a remote server cron job.

  2. 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.

  3. Scratch that I didn’t notice you used them.

  4. I used that code in one of my project and it worked great!

  5. Thanks for the article.
    If your hosting provider doesn’t allow setting cronjobs, there are some services, that will allow cronjob up to each hour for free, like easycron.com


Leave a comment

Best way to periodically execute a PHP script? - PHP Solutions - Developers Q & A