tags:

views:

140

answers:

3

Say I want a php script the run the function itstime() every hour. Other than setting up a cron job on the server how can I do this?

Or is this not possible because php scripts need to be opened to be ran?

Thanks.

EDIT: I want to write some information to a log file and depending on some variables send it in an email.

+2  A: 

Well, I definitely recommend the cron job for the purpose. But theoretically, you could have a PHP script run itstime(), sleep for an hour, and loop. This is pretty crazy, though.

The script would look like:

<?php
include('whatever.php');
while(true) {
    itstime();
    sleep(3600);
}
?>

One would probably run it with nohup php mycrazyscript.php & to detach it from your terminal and make it keep running, and using pkill -f mycrazyscript to terminate it.

The reason this is crazy is that now you've got a sleeping PHP process hanging around doing nothing for 59 minutes out of every hour, and you have to make sure it's both running and running at the right time, both of which cron would take care of for you.

chaos
How would I do that? and why do you say it is crazy?
mrlanrat
Yeah would definitely not be my choice of ways to approach it but if cron is not an option, might be the only alternative.
Christian
If I used this method would that mean then when I visited this page (To start the script) it will never finish loading?If that is the case will the script stop running once the page is exited?
mrlanrat
If you were going to do this, you should run the PHP script from the shell command line, not from the web.
chaos
What if shell is not an option?
mrlanrat
Then get a new web host. No cron and no shell? Come on, this is 2009.
chaos
Okay, yeah, sometimes that's not an option. Try googling for **web based cron**; there are services out there that exist to help with / take advantage of situations like this, by selling you a service where they call a Web script at some regular interval.
chaos
+1  A: 

Only appending to chaos' answer, so give him credit.

mrlanrat - see this

Christian
+1  A: 

If you don't have access to cron, but do have access to a moderately busy webserver, you can use it to trigger your function every hour. This is how WordPress gets around needing cron. Here's how you might do it:

<?php
$lastrun = get_last_run_time(); // get value from database or filesystem
if( time()-$lastrun > 60*60 ) {
  itstime();
  set_last_run_time(time()); // write value back to database or filesystem
}
// The rest of your page
?>

Of course, there's a pretty serious race condition in this code as is. Solving that is left as an exercise to the reader.

scompt.com
This is a good solution however This page/site will not be visited regularly so I do not think it will work in this case.
mrlanrat