Maka
Maka

Reputation:

How to schedule the execution of a PHP script on the server side?

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

Upvotes: 21

Views: 54698

Answers (5)

cletus
cletus

Reputation: 625485

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

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

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

Upvotes: 28

jmoz
jmoz

Reputation: 8006

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

Upvotes: 18

rmeador
rmeador

Reputation: 25724

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.

Upvotes: 7

Phil Rae
Phil Rae

Reputation: 23

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

Upvotes: 1

Shoban
Shoban

Reputation: 23016

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

Upvotes: 2

Related Questions