1

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)?

andrw
  • 790
  • 1
  • 8
  • 20
  • 2
    http://stackoverflow.com/questions/120228/php-running-scheduled-jobs-cron-jobs. For your side question, require a secret query parameter to be present for the script to run. – brian_d Nov 04 '11 at 03:58
  • What version of windows are you using and when is your machine typically turned on? – hafichuk Nov 04 '11 at 04:06
  • I'm using a mac, but I also have a windows 7 desktop. the mac is a laptop so it varies, the desktop is hardly used – andrw Nov 04 '11 at 04:18

3 Answers3

4

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.

Garrett
  • 583
  • 1
  • 4
  • 11
  • on a mac, just navigating to the local file in my browser while running XAMPP (apache, mysql, ftp) – andrw Nov 04 '11 at 04:01
  • Mac runs BSD, so a cronjob will work. The php path maybe different, so just find out that bit and you are good to go. – Jim Nov 04 '11 at 04:05
  • Don't forget the often forgotten and lonely `at` and `batch` commands in *nix. – Yzmir Ramirez Nov 04 '11 at 04:12
1

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

gmhk
  • 15,598
  • 27
  • 89
  • 112
1

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278