tags:

views:

1108

answers:

5

I need a PHP script to be automatically executed at a particular time. How would I achieve this aim?

+9  A: 

If you're running a flavour of Linux/Unix (including Mac OSX), create a cron job.

If you're running Windows, creat a scheduled task.

Note: both of the above links relate specifically to a PHP audience.

cletus
A: 

How to Create a Cron Job (Scheduled Task) for Your Website or Blog if you are on linux.

Shoban
A: 

If you're not using Linux/Unix, ask your host whether they would be able to set up a Windows scheduled job for you. Depending whether you can get through the thicket of some hosts' support departments, they should be happy to as it doesn't necessarily pose a security risk

Phil Rae
+2  A: 

I'm assuming you're creating some kind of webapp and you need part of the system to run something periodically, so it can't be run through a browser. It's a little tricky to do this if you're loading lots of 3rd party libs or using a lot of server functionality, but if it's straight PHP, you can do it very easily. Create a scheduled job of some sort (cron job on Linux, Scheduled Task on Windows, etc) that runs the command php -f filename.php. That will execute your PHP script of choice through the CLI PHP interpreter, which is very similar (perhaps identical to) the way the PHP script would be executed through CGI, but minus some of the server-specific environment variables.

rmeador
+1  A: 

If you edit the crontab manually with crontab -e or go to list it with crontab -l, a useful comment to put at the top of the crontab is below.

# .---------------- minute (0 - 59) 
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
# |  |  |  |  |
# *  *  *  *  *  command to be executed

  30 3  *  *  *  php /home/scripts/do_something.php
jmoz
In some cases thou, depending on what kind of script this "do_something.php" is, it would be better to execute it inside the webserver so the option would be to replace "php /home/scripts/do_something.php" with "wget http://your.domain.com/do_something.php"
rasjani
Sure, if it was web based, then wget the script. Else if it was a PHP cli app, then call it as demonstrated.Either way, I was demonstrating the useful comment.
jmoz