且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何每天执行一个PHP脚本

更新时间:2023-02-22 20:02:31

设置cron作业的方法。假设你有shell访问,你可以从控制台 crontab -e 中定义作业,例如:

There's couple of ways to setup cron job. Assuming you got shell access you could do crontab -e from console and define job there, i.e. like this:

1 22 * * * command

$ c>命令(无论是什么)在22:01每天(不知道为什么你设置分钟 1 而不是 0 虽然)。要从那里启动PHP脚本,您必须安装 php-cli ,然后按照以下方式调用:

which would trigger command (whatever it is) at 22:01 each day (not sure why you set minutes to 1 instead of 0 though). To launch PHP script from there you would either have to install php-cli, and then invoke it that way:

1 22 * * * <path>/php -q script.php

你还可以在这里调用bash脚本,设置所有的东西,如路径等,然后调用你的php脚本形式bash - 有时它更容易做到这一点,而不是制作太长的命令行cron。稍后更新它更简单。也可以通过设置它的执行位( chmod a + x script.php )并在你的脚本中添加shell行作为第一行,将你的php脚本转换为bash-runnable脚本:

You can also call bash script here, to setup all the stuff like paths etc and then call your php script form bash - sometimes it is simpler to do that way instead of crafting way too long command line for cron. And it's simpler to update it later. also, you could turn your php script into bash-runnable script by setting it execution bit (chmod a+x script.php) and adding shell line as 1st line in your script:

#!/usr/bin/php -q
<?php
   ...

如果你的脚本有太多的依赖,你更喜欢通过web调用它, wget 以模仿浏览器。因此您的命令将是:

If your script got too many dependencies and you'd prefer to call it via web, you could use wget to mimic a browser. so your command would be:

/usr/bin/wget --delete-after --quiet --spider <URL-TO-YOUR-SCRIPT>

wget手册可以通过 man wget wget -h ,或者是在此网站上。或者,你可以使用 HEAD 从perl-www包,但它需要perl,而wget是独立工具。如果您使用带自签名证书的HTTPS,请添加 - no-check-certificate 。您还可以设置 .htaccess 并限制对cron脚本的访问localhost / 127.0.0.1

wget manual can be accessed by man wget or wget -h, or is on this website. Aternatively you may use HEAD from perl-www package but it requires perl while wget is standalone tool. If you use HTTPS with self signed certs add --no-check-certificate. And you may also want to setup .htaccess and limit web access to your cron script to localhost/127.0.0.1