Running long-running scripts independently of main script

Hey folks,

An interesting question for somebody.

I’m implementing a “scheduler” feature for a script I develop, that allows external modules that interact with the core script to register things to do at certain times. Basically it’s just a cron jobber, only server independent and no-where near so accurate. So module A could say, “do THIS at THIS frequency”, and the scheduler will take care of it.

To trigger the scheduler to check to see if there’s anything to do, I’m adding a line of code that’ll be executed anytime someone loads the page. Yes, I know this could be hours (or whatever) after the module requested their code be executed, but I think it’s acceptable for my situation.

Now here’s the rub: the code in the scheduler queue could potentially take hours to complete. I don’t want the page load to be slowed down too much. A second or two is acceptable, any longer is not.

So… I figure here are my options:

#1: spawn a child process in PHP. This would be ideal, except my script has to work on the vast majority of web servers, so pctnl_fork() isn’t an option (or can only be used as a fallback), enticing though it may be.

#2: in the page add an image that actually runs the scheduler:

<img src="runScheduler.php" width="0" height="0" />

Anyone have any experience with #2? Does this work for all servers running PHP? Are there any better solutions for #1…? Any other brilliant ideas…? Remember: I need this to run on the lowest common denominator web server.

Thanks very much! :slight_smile:

  • Ben

It’ll work, but the maximum execution time on most hosts is 30-60 seconds, after which the script will be terminated. You can override it on some with set_time_limit, but it’s also not uncommon for hosts to terminate users whose sites spawn long-running processes often.

Make sure you send an image and flush the output buffer to the browser first thing so that the page load isn’t eternally waiting for that image to load. It could mess up javascript on the site.