0

I am calling from my Java EE application through ssh (apache) Powershell script on remote server, this script cannot be run in parallel so I need to check if the script is already running and wait until there is no process and run that waiting script. It might happen that the script will be called several times, eg. 20 times in few seconds and all of these needs to be run one by one.

Any idea how this can be achieved or if this is even possible? Thank you!

Samot
  • 47
  • 6

1 Answers1

2

The way that I've accomplished this in some of my scripts is to use a lock file

  $lockFile = "$PSScriptRoot\LOCK"
    if (-not (Test-Path $lockFile)) {
        New-Item -ItemType File -Path $lockFile | Out-Null
       
        #  Do other stuff...
    
        Remove-Item -Path  $lockFile -Force
    }

You could maybe modify to something like this?

$lockFile = "$PSScriptRoot\LOCK"
while (Test-Path $lockFile)
{
    Start-Sleep -Seconds 2
}

New-Item -ItemType File -Path $lockFile | Out-Null

#  Do other stuff...

Remove-Item -Path  $lockFile -Force
Daniel
  • 4,792
  • 2
  • 7
  • 20
  • This, a flag in the registry, or a flag field in the application's database are all common solutions to this sort of thing. One problem with it is that you will then need a way to force it to reset the flag, because if the thread running the process crashes then it won't unset it and your system can no longer queue the task. – Bacon Bits Feb 10 '21 at 22:26
  • Yes, there is that risk unfortunately. OP, check out the solutions [here](https://stackoverflow.com/questions/15969662/assure-only-1-instance-of-powershell-script-is-running-at-any-given-time) as well – Daniel Feb 10 '21 at 22:48
  • Thank you Daniel, It works great! Sorry for late response, I was focus on other tasks and I just return to this now. – Samot Feb 24 '21 at 11:23