Run PHP file at scheduled times?

风格不统一 提交于 2020-01-05 08:08:31

问题


I have a php file which pulls some data from external API's, and I want to schedule it to do so every few hours (or every few days). Some googleing led me to "scheduled tasks", but it seems I need to be running my own server to do it?

So far, all the PHP and MySQL I've done have been very simple form-filling, so I'm a little lost. Do I need to turn a computer into a server to do this, or should I look into hosts that allow you to run scripts? I'm not exactly sure what I'm looking for.

Side-question: how would I be able to prevent someone else from running the PHP script (therefor making tons of API calls)?


回答1:


How are you running the script now? Windows or Linux? Linux is a no-brainer with cron: on a PHP-enabled server simply drop the PHP script somewhere, edit the crontab and away you go!

Ex. for every 2 hours

0 */2 * * * /usr/local/bin/php /path/to/script.php

Edit Re: Mac

launchd is apparently the preferred method to run scheduled tasks but I understand that OS X has cron capabilities as well being a UNIX derivative.




回答2:


If you have a reasonably busy web server, you can simply check every time how long it has been since the last time you ran the script. If more than two hours, run it.

Just make sure to update the time and run the script atomically so you don't launch several copies of the script. You can do this with a file that contains the last time the script was run that you lock while you check and update it.




回答3:


cronjobs are made for it... You can check the Cron Jobs in cpanel.. I am assuming your website is launched in Linu environment

http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

http://man.cx/cron

You can find much more exlaination about the Background Process

http://www.fijiwebdesign.com/blog/create-a-background-process-on-the-server-with-php.html



来源:https://stackoverflow.com/questions/8004710/run-php-file-at-scheduled-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!