Skip to main content
Inspiring
December 29, 2022
Answered

SDK how to prevent that a plug-in runs twice

  • December 29, 2022
  • 1 reply
  • 381 views

I created a plug-in which might take some time to finish dependant upon the number of photos selected.

Question: how I can prevent that the plug-in is started anew while it is already running?

 

Currently I update the LRPrefs at the start and again when the plugin finishes.
However I don't like this solution, because sometimes, due to an error, the plugin quits and then the 2nd LrPrefs call is never made and the plugin prevents to start. Ofcourse that can be reset, but I would like to know if there is a better way that the plugin itself can detect that it is already running.

This topic has been closed for replies.
Correct answer johnrellis

You could use a global boolean "running". All instances of a plugin share the same global environment, so they'll see the same variable.

 

You can make sure that an instance always sets "running" to false no matter how it exits by using a cleanup handler (similar to try/finally in other languages but clunkier):

local function main (context)
    context:addCleanupHandler (function ()
        running = false
        end)
    if running then return end
    running = true 
    ...
    end

LrFunctionContext.callWithContext ("", main)

 

1 reply

johnrellis
johnrellisCorrect answer
Legend
December 30, 2022

You could use a global boolean "running". All instances of a plugin share the same global environment, so they'll see the same variable.

 

You can make sure that an instance always sets "running" to false no matter how it exits by using a cleanup handler (similar to try/finally in other languages but clunkier):

local function main (context)
    context:addCleanupHandler (function ()
        running = false
        end)
    if running then return end
    running = true 
    ...
    end

LrFunctionContext.callWithContext ("", main)

 

Inspiring
December 31, 2022

Minor update. When adding the code above to a second menu option in the same plug-in, it turns out that adding context:addCleanupHandler triggers setting running to false.

However when I first check running then everything works fine.

 

local function main (context)
    if running then return end
    context:addCleanupHandler (function ()
        running = false
        end)
    running = true 
    ...
    end

LrFunctionContext.callWithContext ("", main)
johnrellis
Legend
December 31, 2022

That looks right.