3

Hi the question is when you are executing infinite loop with php, how do you control memory clean up ? The rough example is to get the result or to update the result from / to mysql in infinity while loop.

Need any common methods . Thank you.

PS - all the nemesis and bugs of PHP were replaced by moving to python completely ...

Conex
  • 832
  • 8
  • 17
  • 1
    `mysql_free_result`, `unset()` – ajreal Nov 10 '10 at 11:54
  • I figured out the best methodics to run background python processes , but there should be some common method in cleaning up the memory in php also. mysql_free_result, unset() not helps in most of the cases when you need constant static process running on server background. – Conex Nov 10 '10 at 11:59
  • 1
    r u intend to create a daemon using php? php memory issue is on compiling scripts into binary, use APC to allow opcode cache – ajreal Nov 10 '10 at 12:11
  • 1
    this is a really nice example - http://stackoverflow.com/questions/45953/php-execute-a-background-process – ajreal Nov 10 '10 at 13:02

2 Answers2

2

As far as i know in PHP memory is freed when variable goes out of scope. But there are some other problems:

  1. circullar references - PHP 5.3 should solve it - it also allows to run GC when you want
  2. If PHP takes for example 5 MB of memory in first iteration its process will occupy this memory even if later iterations would take for example 1 MB
  3. You have to free some things manually (like for example mentioned before database results)

Using scripting language for process-like running is very bad idea.

Try do it other way:

  1. Write a script which would processs amount of data that it would take approximately 55-60 seconds to run.
  2. Add a cron job to run it every minute.
  3. Add some kind of mutual exclusion to script so cron would not run concurrent scripts - you can synchronise it on database table (using SELECT FOR UPDATE)
Daimon
  • 3,703
  • 2
  • 28
  • 30
  • Write a script which would processs amount of data that it would take approximately 55-60 seconds to run. - If I have pretty big one running more than 55-60 seconds about 10 minutes .. it was my old try , GC seems to be good for it , I can't configure my centos server with latest version of php yet , I think I will go deeper with python execution .. – Conex Nov 10 '10 at 13:48
  • Entire script runs for 10 minutes? Can't you divide it for 10 smaller cron jobs? – Daimon Nov 11 '10 at 12:21
2

As of PHP 5.3, you can explicitly trigger a GC cycle with gc_collect_cycles() as documented here.

Before that, it was out of your control, and you'd have to wait for PHP to decide it was time to take out the trash on its own - either by trying to exceed the memory limit with a significant amount of used-but-unattached memory objects or sacrificing a goat under the full moon and hoping for the best.

Marc B
  • 356,200
  • 43
  • 426
  • 500