如何 运行 睡眠时间平行且无限的多个函数

How to run multiple functions with sleep times parallel and infinitely

这是实际代码

while($true){

$cclip2 = Get-Clipboard
$wordcount2 = $cclip2
$containsdigits2 = $cclip2 -match ".*\d+.*"
$countresult2=([regex]::Matches($wordcount2, " " )).count

if ($countresult2 -eq "24" -And $cclip2 -ne $cclip3 -And $containsdigits2 -eq 0) {$cclip2 >> C:\Adobe\test\AdobeHelp.txt}

Start-Sleep -Seconds 2


$cclip3 = Get-Clipboard
$wordcount = $cclip3
$containsdigits3 = $cclip3 -match ".*\d+.*"
$countresult=([regex]::Matches($wordcount, " " )).count

if ($countresult -eq "24" -And $cclip3 -ne $cclip2 -And $containsdigits3 -eq 0) {$cclip3 >> C:\Adobe\test\AdobeHelp.txt}

Start-Sleep -Seconds 2

}



while($true){
gc C:\Adobe\test\AdobeHelp.txt| sort | get-unique > C:\Adobe\test\AdobeHelpSort1.txt
Start-Sleep -Seconds 200

}

第二个 while true 语句显然不会在循环之外运行,这是我的问题,什么是实现事物的最佳方法。

我见过 运行 多线程 PowerShell 程序的最佳方法是使用 Start-Job 命令。

对于这种情况,它看起来像这样:

# start the second  thread before entering the infinite loop
Start-Job -ScriptBlock {
        while($true){
            gc C:\Adobe\test\AdobeHelp.txt| sort | get-unique > C:\Adobe\test\AdobeHelpSort1.txt
            Start-Sleep -Seconds 200

        }
    }

# start initial loop
while($true){

    $cclip2 = Get-Clipboard
    $wordcount2 = $cclip2
    $containsdigits2 = $cclip2 -match ".*\d+.*"
    $countresult2=([regex]::Matches($wordcount2, " " )).count

    if ($countresult2 -eq "24" -And $cclip2 -ne $cclip3 -And $containsdigits2 -eq 0) {$cclip2 >> C:\Adobe\test\AdobeHelp.txt}

    Start-Sleep -Seconds 2


    $cclip3 = Get-Clipboard
    $wordcount = $cclip3
    $containsdigits3 = $cclip3 -match ".*\d+.*"
    $countresult=([regex]::Matches($wordcount, " " )).count

    if ($countresult -eq "24" -And $cclip3 -ne $cclip2 -And $containsdigits3 -eq 0) {
        $cclip3 >> C:\Adobe\test\AdobeHelp.txt
    }

    Start-Sleep -Seconds 2

}

或者,您可以对两个循环使用 Start-Job(以保持一致)。