Question

I have a php script that reads one file through http(the file is on other domain). I would like to read this file only once or twice a day, instead of connecting to it every time the website is refreshed. Is there any other way than doing it with cron? I dont want to use cron cause I prefer to setup this behaviour in the script itself .. so it is flexible, so I can use it anywhere without setting up cron every time. thanks

Was it helpful?

Solution

If you can't or don't want to use use cron and it's ok to update it only when the page is accessed. You could cache the result of the HTTP request and only update it on a page load it if the cache is older than a day or whatever interval you choose.

OTHER TIPS

I've done this kind of thing in the past when I didn't have access to cron:

$lastRunLog = '/path/to/lastrun.log';
if (file_exists($lastRunLog)) {
    $lastRun = file_get_contents($lastRunLog);
    if (time() - $lastRun >= 86400) {
         //its been more than a day so run our external file
         $cron = file_get_contents('http://example.com/external/file.php');

         //update lastrun.log with current time
         file_put_contents($lastRunLog, time());
    }
}

You can also use Web Based Cron if you want to hit a site on a timed interval.

You could even use a database table - really simple in structure, id, date, script url, and whatever you need - and add a row every time you run the script.

Then, before run the script simply check the numbers of row for each day you have.

You can use a Cronjob. You can then run the php script by the command line.

php /someplace/somefile.php

The Cronjob would be the following if you update every day.

0  0  *  0  0  php /someplace/somefile.php

Since you explicitly state that you don't want to use cron, the only other way to do this (without something analogous to cron) is to set up your script as a daemon. However, unless you really need the flexibility that daemons provide, cron is much easier and simpler.

Here's one daemon walk-through.

If you're using a Linux distro with systemd:

I had a need for scheduling yearly based jobs, independent of the application (in case the system rebooted or anything like that), and I was given the suggestion to use systemd Timers. The Arch Wiki Page on it gives some examples.

If you are on a *nix environment you can use cron jobs

What's wrong with cron?

You have a couple choices with cron - your php can be invoked by the command line PHP interpreter, or you could use wget or fetch or the equivalent to invoke your PHP on the server.

In general, PHP run from within the context of the web server has a time limit on how long it can execute, so in general you can't set up "background" PHP threads to do stuff "later".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top