首页 > 解决方案 > 如何为特定值只触发一次 Timer

问题描述

由于没有真正好的即时加密货币价格警报应用程序,我自己做。将警报发送到手机时我很挣扎,因为我希望计时器为我选择的每个值触发一次。我通过 Pushbullet API 将警报发送到我的手机,我不想让它泛滥。

我正在通过 timer1 的在线 API 实时解析“价格”。一切正常,但 timer2. 显然,计时器 1 每 5 秒计时一次,以检查价格是否高于我选择的值,但如果价格高于所选值,那么它会在每次滴答时通过 PushBullet 发送警报。我怎样才能让 timer1 检查价格是否高于价值,如果是,只勾选一个?我得到的最接近的想法是:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
       If CInt(price) > 0.05060 Then
           timer2.start
       ElseIf CInt(price) > 0.05080 Then
            timer2.start
        ElseIf CInt(price) < 0.04960 Then
            timer2.start
       End If
  
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
       Pushbullet("Price above 0.05060") 
       '[....]
       '[....]
       Timer2.Stop()
   End Sub

显然,重要的是不要停止 timer1,而是停止 timer2。但是我该如何管理呢?我很坚持。任何想法?谢谢

标签: vb.net

解决方案


Private previousPrice As Double

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If (price > 0.05060 AndAlso previousPrice <= 0.05060) OrElse
       (price > 0.05080 AndAlso previousPrice <= 0.05080) OrElse
       (price < 0.04960 AndAlso previousPrice >= 0.04960)
        timer2.Start()
    End If

    previousPrice = price

我在那里使用了 type Double,因为你在你的代码中做了,但这些值真的应该是 type Decimal

您也可以考虑不对这些值进行硬编码,以便无需重新编译即可轻松更改它们,例如

Private upperThresholds As New List(Of Double) From {0.05060, 0.05080}
Private lowerThresholds As New List(Of Double) From {0.04960}
Private previousPrice As Double

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If upperThresholds.Any(Function(threshold) price > threshold AndAlso previousPrice <= threshold) OrElse
       lowerThresholds.Any(Function(threshold) price < threshold AndAlso previousPrice >= threshold)
        timer2.Start()
    End If

    previousPrice = price

现在,您可以根据需要在这些列表中添加、编辑和删除值。


推荐阅读