Running a Script as a Cron Job
3 posts by 2 authors in: Forums > CMS Builder
Last Post: April 2, 2015 (RSS)
By Perchpole - April 2, 2015
Hi, All
I am having one of those brain-ache days where I can't quite get my head around what I'm trying to do...
One or two scripts on my site are a bit heavy so I've hit upon the idea of running each one daily via a cron job. The questions I have are:
1) How do I output the results?
2) How do I feed the results back into my web pages?
If the script were running through a page on the site it would output an array. I could then loop through the results as normal. However, if cron is running the script and saving the results to a file, how do I then feed that data back into my page?
My head hurts...!
:o)
Perch
By Perchpole - April 2, 2015
Hello, All
Right! As usual I've had a determined but possibly ham-fisted stab at trying to work out my own problem. This is what I've done (which may explain what I was trying to achieve!)...
Cron runs once a day and executes the following script:
$query = mysql_query("SELECT num, title, etc...);
while( $row = mysql_fetch_assoc($query)){
$new_array[] = $row;
}
$serializedData = serialize($new_array);
file_put_contents('../path/filename.php', $serializedData);
So the script runs a query and outputs the array to a file which is saved on the server.
In my webpage I have the following code which collects the data and feeds it back into another script:
<?php
$recoveredData = file_get_contents('../path/filename.php');
$recoveredArray = unserialize($recoveredData);
?>
<?php foreach($recoveredArray as $recovered): ?>
<?php echo $recovered['title'] ?>
etc...
<?php endforeach ?>
It seems to work. The question now is, is this the right way to do it? Are there other, better, more secure ways of achieving the same thing?
Perch
By gregThomas - April 2, 2015
Hey Perch,
This could be a good method to use if the MySQL calls you're making are extremely complex, but if it's fairly straight forward requests you're probably best sticking to getting the data directly from the MySQL database.
This is because MySQL can cache popular requests to memory so that the data is retrieved quickly, and is designed to handle lots of simultaneous requests.
I found this stack overflow post that goes over the reasons in more detail:
http://stackoverflow.com/questions/20269940/php-read-file-vs-mysql-query
Thanks!
Greg
PHP Programmer - interactivetools.com