Skip to content

Instantly share code, notes, and snippets.

@opensourcelib
Created January 18, 2016 14:54

Revisions

  1. jelqui created this gist Jan 18, 2016.
    66 changes: 66 additions & 0 deletions Lockmagentoprocess.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    <?php

    class Lockmagentoprocess
    {
    /**
    * Our process ID.
    */
    const PROCESS_ID = 'ProcessId';

    /**
    * Mage_Index_Model_Process will provide us a lock file API.
    *
    * @var Mage_Index_Model_Process $indexProcess
    */
    private $indexProcess;

    /**
    * Constructor. Instantiate the Process model, and set our custom
    * batch process ID.
    */
    public function __construct()
    {
    $this->indexProcess = new Mage_Index_Model_Process();

    $this->indexProcess->setId(self::PROCESS_ID);
    }

    /**
    * Process all the things!
    */
    public function changeEverything()
    {
    if ($this->indexProcess->isLocked())
    {
    $this->log(sprintf("Another %s process is running! Abort", self::PROCESS_ID));
    return false;
    }

    // Set an exclusive lock.
    $this->indexProcess->lockAndBlock();

    $this->log("Starting...hold on to your hats.");

    for ($i = 1; $i < 1000; $i++)
    {
    // Do something complicated with $i.
    }

    $this->log("Finished! Whew.");

    // Remove the lock.
    $this->indexProcess->unlock();

    return true;
    }

    /**
    * Log a message to stdout.
    *
    * @param $msg
    */
    public function log($msg)
    {
    echo $msg . PHP_EOL;
    }
    }