Michael Weaver
Michael Weaver

Reputation: 23

Run PHP function indefinitely - run function directly after it has just finished

I have a PHP function which hits an API and pulls in data. This takes around 6 hours. Rather than playing around with cron-job timing, what I want is for the function to run directly after it has just finished.

For instance...

<?php
function run_for_six_hours() {
    // runs for six hours
    copy_of_the_above_function();
}

function copy_of_the_above_function() {
    // do the same thing again
    run_for_six_hours()
}

Would this method above work, or is there a better method?

I already have done some research and I know running PHP indefinetely isn't best practice, but for this instance we currently don't have a better option.

Upvotes: 1

Views: 533

Answers (2)

Pedro Caseiro
Pedro Caseiro

Reputation: 495

Edit: use the above solution as described by IMSoP

If you are aware of the consequences and what you need to setup to get the script to run indefinitely, you can just call the same function again:

function run_for_six_hours() {
    // runs for six hours
    run_for_six_hours();
}

Upvotes: 2

IMSoP
IMSoP

Reputation: 97678

The method you have described is infinite recursion - the function calls itself repeatedly (technically, what you have is "mutual recursion", because you have the extra wrapper copy_of_the_above_function, which isn't necessary). The problem with that is that in most languages (including PHP), each call stores its state on the stack until everything inside it returns, so you will have a stack like run_for_six_hours -> copy_of_the_above_function -> run_for_six_hours -> copy_of_the_above_function -> run_for_six_hours -> copy_of_the_above_function -> ... getting longer and longer. Eventually, PHP will hit a limit (either memory, or the maximum stack depth) and crash.

A much simpler method is just to put the function in an infinite loop:

while ( true ) {
    run_for_six_hours();
}

PHP will wait for the function to complete, run it again, and again, and again. As long as there's no memory leaks in the implementation, this will run indefinitely. You will need to disable PHP's max_execution_time setting by setting it to 0 (run forever).

However, if the script crashes for any reason, it won't restart until you log in and run it again. A better approach is to have a script that runs the code once, and use an external program to repeatedly run the script. Supervisor is built for exactly this purpose - think of it as like cron, but instead of "run at a specified time", you say "make sure it's always running".

Upvotes: 7

Related Questions