Search code examples
phpjavascriptcroncron-task

cronjob help - need to update clients website "real time"


I am stuck with a project, its a quick fix project & i need some expert help on this please. My clients has two separate websites.

1. http://abc123.com/using-cron-job-update-this-folder.txt <-- I'm working on this
2. http://bw.aaaaaa.com/blah.txt                           <-- Client's 2nd site where some txt gets updated almost twice a day, on this folder blah.txt

I need a php snippet to execute a cronjob, i.e grab text from site2 - http://bw.aaaaaa.com/blah.txt, real time & update site1 - http://abc123.com/using-cron-job-update-this-folder.txt as soon as any text is updated on site 1.


Solution

  • Though this will probably result in high server resource usage and is not very recommended, you can proceed the following way.

    1. The server that will grab the file from another server - let's name it CLIENT.
    2. The server that will contain the new information to be copied by the CLIENT - let's name it SERVER.

    On the CLIENT, create a PHP script that uses CURL to download the remote file's headers only and more specifically the modify-date.

    The following answer provides a useful snippet.

    Store this date and the next time the script runs, check if it's updated, then download the full source, including body and save it however you like (e.g. to a local txt file on the CLIENT).

    Again on the CLIENT, create a cronjob that will run every second or every 5 seconds or however often you like the content to be updated. This may come in handy for setting up the cronjob.

    Alternatively, you may create a single PHP script that will loop and do something (download the remote file) and sleep for 1 second, doing this for a total of 60 seconds then stopping. Combine this with a cronjob that runs every minute and you have yourself the same effect, without having a cron call to the CLIENT server every second. To see an implementation of this approach, see this question and its accepted answer.

    A better and recommended alternative is to use AJAX, which is run on the client side. Make it run as soon as the user's mouse moves and pull date from the SERVER through an API you can expose on the SERVER's side (e.g. one that will return data in JSON format, to be parsed by a JavaScript library like jQuery inside the user's browser). The Facebook Wall is coded this way. If you just leave the Wall open in a background tab it doesn't load any new content. As soon as you switch back to it and hover with the mouse the new posts are displayed.