When a custom Magento cron job runs longer than its configured interval, another execution may start while the previous one is still working. For imports, exports or other write operations, that can lead to duplicate processing or conflicting writes.
Magento already provides a suitable mechanism through the LockManagerInterface . Acquire a lock before starting the main operation. If the lock already exists, the second execution can exit immediately.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
use Magento\Framework\Lock\LockManagerInterface; class Import { public function __construct( private LockManagerInterface $lockManager ) { } public function execute(): void { $lockName = 'vendor_module_import'; if (!$this->lockManager->lock($lockName, 0)) { return; } try { // Run import } finally { $this->lockManager->unlock($lockName); } } } |
The lock name should uniquely identify the process. While vendor_module_import is locked, another run with the same lock cannot begin at the same time.
The important part is the finally: Even if the cron job throws an exception, the lock is released afterwards.
Magento uses its lock mechanism internally in several places. For longer-running custom cron jobs, LockManagerInterface is cleaner and safer than a homemade status file or a flag in the database.