powershell定时器无法立即停止

问题描述 投票:0回答:2

我正在尝试使用 powershell Timer 执行一些定期作业,一旦作业返回满足我期望的结果,我将停止运行该作业。

>$timer = New-Object System.Timers.Timer
>$counter = 0
>$timer.Interval = 1000
>$timer.AutoReset = $true
>Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { if ( $counter -eq 5 ) {$timer.Stop(); } ; $counter = $counter +1; write-host "counter is: " $counter; }
>$timer.Start()

结果是:

 counter is:  1
 counter is:  2
 counter is:  3
 counter is:  4
 counter is:  5
 counter is:  6

我原以为计时器会在 $counter 达到 5 时停止,但它仍然继续工作。有没有办法在满足某些条件后立即停止计时器?

powershell timer
2个回答
0
投票

你的 IF 应该有一个 ELSE。你的逻辑不正确。尝试这样的代码:

$timer = New-Object System.Timers.Timer
$counter = 0
$timer.Interval = 1000
$timer.AutoReset = $true
$wait = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { if ( $counter -eq 5 ) {$timer.Stop(); write-host "counter stopped"; $global:wait=$false } else {$counter = $counter +1; write-host "counter is: " $counter; }}
$timer.Start()

while ($wait) { "sleeping..."; Start-Sleep -Milliseconds 500 }
$timer.Close()
"exiting..."

输出

在我的机器上显示:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
13     3a8d73a2-589...                 NotStarted    False                                 if ( $counter -eq 5 )...
sleeping...
sleeping...
counter is:  1
sleeping...
sleeping...
counter is:  2
sleeping...
sleeping...
counter is:  3
sleeping...
sleeping...
counter is:  4
sleeping...
sleeping...
counter is:  5
sleeping...
sleeping...
counter stopped
sleeping...
exiting...

0
投票

抱歉回复有点晚了
我认为这个问题只是指令顺序造成的。
我认为计时器工作得很好,一旦满足条件,它就会立即停止。
问题是,当计数器达到 5 的值时,计时器确实停止,但后来该计数器增加到 6,但仍然打印为 6

对于

-Action
参数,提供了此指令块

{ 
    if($counter -eq 5) {
        $timer.Stop(); 
    } 
    $counter = $counter +1; 
    write-host "counter is: " $counter; 
}

我建议将此指令块替换为以下内容,首先写入计数器,然后检查它以停止计时器

{ 
    $counter = $counter +1; 
    write-host "counter is: " $counter; 
    if($counter -eq 5) {
        $timer.Stop(); 
    } 
}

所以在这样输入之后

Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { $counter = $counter +1; write-host "counter is: " $counter;   if($counter -eq 5) { $timer.Stop(); } }

结果变得正确:

counter is:  1  
counter is:  2  
counter is:  3  
counter is:  4  
counter is:  5  
© www.soinside.com 2019 - 2024. All rights reserved.