Public/ps1/Job/Start-ApprxrRemoteJobThread.ps1


$threadPreparation = 
{
    #import-module Apprxr

}

# This is the main entry point
<#
    .SYNOPSIS
    Starts a remote job thread for a specified Apprxr pipeline.
 
    .DESCRIPTION
    Manages background jobs for the given pipeline name, stopping any non-running jobs and starting a new job thread as needed.
 
    .PARAMETER name
    The name of the pipeline for which to start the remote job thread.
 
    .EXAMPLE
    Start-ApprxrRemoteJobThread -name 'Pipeline1'
 
    .NOTES
    Used for managing and running remote job threads in Apprxr automation.
#>

function Start-ApprxrRemoteJobThread {                                                                                                                                                
    param ($name)
    try {
    
        $runningProcesses = (Get-Job   -ErrorAction SilentlyContinue) | Where-object {$_.Name.Contains(("Apprxr"+$name))}
    
        $runningProcesses | Where-Object {$_.State -ne "Running"} | %{
            Stop-Job $_ #-ErrorAction SilentlyContinue
            Remove-Job $_# -ErrorAction SilentlyContinue    
        }

        $runningProcesses = (Get-Job   -ErrorAction SilentlyContinue) | Where-object {$_.Name.Contains(("Apprxr"+$name))}


        if (($runningProcesses | Where-Object {$_.State -eq "Running"}).Count -ge 1)
        {
            return
        } else {
            $extension = [int]([int](Get-Date -UFormat %s -Millisecond 0) / 60)

            $directProcessing = Get-ApprxrConfigurationValue -name ($name+"DirectProcessing") -defaultValue $false
            # Start-Job -InitializationScript $threadPreparation -Name ("Apprxr"+$name+$extension) -ScriptBlock {
            Start-Job -Name ("Apprxr"+$name+$extension) -ScriptBlock {
                param ($sleepTime, $pipeline, $directProcessing)
        
                import-module Apprxr   -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
                while ($true) {
                    $result = Get-ApprxrRemoteJob -pipeline $pipeline
                    [system.gc]::Collect()

                    
                    Log "$pipeline : Getting job $directProcessing and result $result waiting for $sleepTime"

                    if ($directProcessing -and $result -eq $false) {
                        Start-Sleep -seconds $sleepTime
                    } elseif ($directProcessing -and $result) {
                    } else {
                        Start-Sleep -seconds $sleepTime
                    }
                
                }
            } -ArgumentList (Get-ApprxrConfigurationValue -name ($name+"Sleep") -defaultValue 10), $name,  $directProcessing

            Log "Starting job instance $(("Apprxr"+$name+$extension))"

        } 
       
    } catch {
        Log $_
    }
}