简体   繁体   中英

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?

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.

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

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'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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM