如何在服务器端调度 PHP 脚本的执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1194857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:27:53  来源:igfitidea点击:

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

php

提问by cletus

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

我需要一个在特定时间自动执行的 PHP 脚本。我将如何实现这个目标?

回答by cletus

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

如果您正在运行某种 Linux/Unix(包括 Mac OSX),请创建一个 cron 作业

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

如果您运行的是 Windows,请创建计划任务

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

注意:以上两个链接都专门针对 PHP 受众。

回答by jmoz

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.

如果您使用 crontab -e 手动编辑 crontab 或使用 crontab -l 列出它,那么放在 crontab 顶部的有用注释如下。

# .---------------- 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

回答by rmeador

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.

我假设您正在创建某种 web 应用程序,并且您需要系统的一部分来定期运行某些东西,因此它不能通过浏览器运行。如果您要加载大量 3rd 方库或使用大量服务器功能,则执行此操作有点棘手,但如果是纯 PHP,则可以非常轻松地完成。创建运行命令的某种计划作业(Linux 上的 cron 作业、Windows 上的计划任务等)php -f filename.php。这将通过 CLI PHP 解释器执行您选择的 PHP 脚本,这与通过 CGI 执行 PHP 脚本的方式非常相似(可能相同),但减去了一些特定于服务器的环境变量。

回答by Phil Rae

If you're notusing 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

如果您使用 Linux/Unix,请询问您的主机是否能够为您设置 Windows 计划作业。取决于您是否可以通过一些主机支持部门的丛林,他们应该很乐意,因为它不一定会带来安全风险