Skip to content

Commit 334222f

Browse files
committed
Remove old items in chunks to avoid running out of memory when loading item collection.
1 parent 1b6fa18 commit 334222f

1 file changed

Lines changed: 45 additions & 2 deletions

File tree

  • src/app/code/community/FireGento/AdminMonitoring/Model

src/app/code/community/FireGento/AdminMonitoring/Model/Clean.php

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,21 @@
2727
*/
2828
class FireGento_AdminMonitoring_Model_Clean
2929
{
30-
const XML_PATH_ADMINMONITORING_INTERVAL = 'admin/firegento_adminmonitoring/interval';
30+
const XML_PATH_ADMINMONITORING_INTERVAL = 'admin/firegento_adminmonitoring/interval';
3131
const XML_PATH_ADMINMONITORING_CLEAN_ENABLED = 'admin/firegento_adminmonitoring/enable_cleaning';
3232

33+
/**
34+
* Clean in chunks.
35+
*
36+
* CHUNK_SIZE determines the items cleared per chunk.
37+
*
38+
* CHUNK_RUNS determines the number of chunks cleaned per call to clean()
39+
*
40+
* I.e. per call of clean(), at most CHUNK_SIZE * CHUNK_RUNS items are cleaned.
41+
*/
42+
const CHUNK_SIZE = 1000;
43+
const CHUNK_RUNS = 250;
44+
3345
/**
3446
* Cronjob method for cleaning the database table.
3547
*
@@ -63,22 +75,53 @@ public function clean()
6375
return $this;
6476
}
6577

78+
$this->cleanInChunks();
79+
80+
return $this;
81+
}
82+
83+
/**
84+
* Clean the database table for the given interval, usink chunks to avoid memory over-usage.
85+
*
86+
* @return $this
87+
*/
88+
protected function cleanInChunks()
89+
{
90+
$numChunks = 0;
91+
do {
92+
$cleanedItems = $this->cleanChunk();
93+
} while ($cleanedItems == static::CHUNK_SIZE && $numChunks++ < static::CHUNK_RUNS);
94+
95+
return $this;
96+
}
97+
98+
/**
99+
* Clean a chunk of the items in database table for the given interval.
100+
*
101+
* @return int Number of items deleted
102+
*/
103+
protected function cleanChunk()
104+
{
66105
$interval = Mage::getStoreConfig(self::XML_PATH_ADMINMONITORING_INTERVAL);
67106

68107
/* @var $adminMonitoringCollection FireGento_AdminMonitoring_Model_Resource_History_Collection */
69108
$adminMonitoringCollection = Mage::getModel('firegento_adminmonitoring/history')
70109
->getCollection()
110+
->setPageSize(static::CHUNK_SIZE)
71111
->addFieldToFilter(
72112
'created_at',
73113
array(
74114
'lt' => new Zend_Db_Expr("DATE_SUB('" . now() . "', INTERVAL " . (int) $interval . " DAY)")
75115
)
76116
);
77117

118+
$count = 0;
119+
78120
foreach ($adminMonitoringCollection as $history) {
79121
$history->delete();
122+
$count++;
80123
}
81124

82-
return $this;
125+
return $count;
83126
}
84127
}

0 commit comments

Comments
 (0)