我想使用cronjob导入产品。但问题是当导入作业同时运行两次时。 我怎样才能保护这些? 我试着这样做:
private function isImportAlreadyRunning()
{
$isRunning = false;
$cronSchecduleCollection = Mage::getModel('cron/schedule')->getCollection()
->addFieldToSelect(array('job_code', 'status'))
->addFieldToFilter('job_code', array('eq' => 'my_import_products'))
->addFieldToFilter('status', array('eq' => 'pending'))
->addFieldToFilter('executed_at', array('neq' => 'NULL'))
->load();
Mage::log('Cron size: ' .$cronSchecduleCollection->getSize());
if($cronSchecduleCollection->getSize() > 1)
{
$isRunning = true;
}
return $isRunning;
}
但这些不起作用,因为$ cronSchecduleCollection-> getSize()等于1,即使我同时运行2个进程。 Class是singleton,因为它属于Helper。
答案 0 :(得分:0)
你需要"锁定"数据库。我使用那种功能:
private function _takeLock() {
$result = false;
$st = $this->_dbCntr->query('select is_free_lock("BMS_PRODUCT_IMPORT");');
if ($st->fetchColumn() == 1){
$st2 = $this->_dbCntr->query('select get_lock("BMS_PRODUCT_IMPORT", 0);');
$result = $st2->fetchColumn() == 1;
}
return $result;
}
private function _releaseLock() {
$this->_dbCntr->query('select release_lock("BMS_PRODUCT_IMPORT");');
}
然后:
$this->_dbCntr = Mage::getSingleton('core/resource')->getConnection('core_write');
// Take a lock
if (!$this->_takeLock()) {
return 'Process already running. Aborting';
}
process of import
$this->_releaseLock();