I need a PHP script to be automatically executed at a particular time. How would I achieve this aim?
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.
How to Create a Cron Job (Scheduled Task) for Your Website or Blog if you are on linux.
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
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.
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