How To Run PHP Code In The Background on unix server

后端 未结 3 757
清酒与你
清酒与你 2020-12-11 08:54

In my web site I have some feature to upload data feeds by users. These data feeds normally having more than 30,000 records. And each records need to be go through complex v

相关标签:
3条回答
  • 2020-12-11 09:32

    PHP is not designed for this kind of job. But there are tricks to try doing it.

    If your feeds have more than 30,000 records each, you will have timeout problems with PHP FPM. So your script must run with PHP CLI (Check your server parameters for PHP CLI timeout).

    You should look at Rabbit MQ and program a cron job each minute to consume messages in the queue. Here an example with PHP http://www.rabbitmq.com/tutorials/tutorial-two-php.html

    Hope that will help you

    0 讨论(0)
  • 2020-12-11 09:47

    At last I got a working answer from following post: php exec command (or similar) to not wait for result

    So I edit the code as follows to get my requirement working. But I don't know the explanation how it work. I only copy the syntax from that answer and past it here with modification.

    <?php 
    echo "Script start at: " . date('h:i:s') . "\n"; 
    exec('bash -c "exec nohup php createfile.php > /dev/null 2>&1 &"');
    echo "Script end at: " . date('h:i:s'); 
    ?>
    

    Here php createfile.php will be the command to execute the PHP script and continue without waiting to output.

    Thanks to Cristian

    0 讨论(0)
  • 2020-12-11 09:52

    Use exec()

    http://php.net/manual/en/function.exec.php

    This will allow you to run the long process in another thread. I've used this to all other PHP, Python or C apps to convert wav to mp3, video conversion, or parsing through large XML files...

    Be sure to have it notify you or the user, probably via email, when it completes, and if it was successful.

    EDITED with working code at purehuman.info/demo ... it actually writes the file now. This is what I would make thread.php look like:

    <?php 
        echo "Script start at: " . date('h:i:s') . "\n"; 
        exec("php -f  createfile.php /dev/null &"); 
        echo "Script end at: " . date('h:i:s'); 
    ?> 
    

    If you are in windows:

    <?php 
        echo "Script start at: " . date('h:i:s') . "\n"; 
        exec("start /B php createfile.php"); //obviously change the paths etc where needed..
        echo "Script end at: " . date('h:i:s'); 
    ?> 
    

    need to give credit for the windows part: How to execue PHP scripts in the background using EXEC() and CMD

    0 讨论(0)
提交回复
热议问题