I wanted to iterate over 1000 database records in my Laravel application to fetch Google analytics data for each individual record. Connection with Google Analytics API closes approximately after 1 hour hence I can not iterate over all these 1000 records at a time using foreach loop. I can Iterate over approx 350 records at a time e.g. within this 1 hour timeframe.
I want to run my PHP code using scheduler e.g. nginx crontab. I wanted to know how to process first 350 records at particular time of scheduler, then next 350 records at another time frame of scheduler and so on.
The one way to achieve this is using three separate files which will contain same logic for processing different records and scheduling individual file at different crontab time frame.
But Instead of creating 3 separate files, I wanted to use single file to process all the 1000 records at different time frame using Crontab. Is there any way to achieve this?
Below is my code snippet:
$models = DB::table('gatestmodels')
->join('carmodels', 'gatestmodels.ID', '=', 'carmodels.ID' )
->select('gatestmodels.ID', 'gatestmodels.MaskingName')
->where('CarMakeId', $make->ID)
->OrderBy('gatestmodels.ID')
->get()
;
foreach($models as $model)
{
$segment = "sessions::condition::ga:pagePath=~/".$make->MaskingName."-cars/".$model->MaskingName."/";
$data = $analytics
->data_ga
->get(
'ga:' . $this->profile_ids[0],
$this->start_date,
$this->end_date,
$metrics,
$segment
)
;
}
If you want it to set it as a single file there are two ways of my knowledge.
1) You can add a column is_analytics_done default to 0 and update it to 1 after analytics done and while getting records you can get first 350 records of is_analytics_done = 0 in your query
2) If you set cron job to execute every 2 hours you can have a switch case in cron file by getting current time
<?php
$getCurrentTime = Carbon::now()->hour;
switch ($getCurrentTime) {
case '2':
// get first 350 records
break;
case '4':
// get second 350 records
break;
case '6':
// get third 350 records
break;
}