草庐IT

algorithm - 进入循环倒数计时器

coder 2023-07-02 原文

我目前有这段代码试图计算触发特定条件的耗时。 (伪):

timeDelay = 900000 // time.Microsecond
for {
   // if a certain something happens, start a counting (time)
   if (certainSomething) {
      startTime = time.Now();

      if !prevTime.IsZero() {
        // add the time elapsed time to timeTick
        diffTime = time.Since(prevTime)
        timeTick = timeTick + diffTime
      }

      prevTime = startTime
   }

   if (timeTick < timeDelay) { // lessThan()
      // still has not reached target count (time elapsed)
      fmt.Println("Not Yet")
      // we dont want to get to the end of the loop yet
      continue
   }

   if (timeTick > timeDelay) { // greaterThan()
      // has finally reached the target count (time elapsed)
      fmt.Println("Yes! Finally")
      // yes the delay has been reached lets reset the time
      // and if `thisHappened` is triggered again, lets start counting again
      timeTick = time.Duration(0 * time.Microsecond)
   }

   // function shouldn't be called if the elapsed amount
   //      of time required has not yet been reached
   iShouldOnlyBeCalledWhenDelayHasBeenReached();
}

我还将这些用作辅助函数(实际代码)

func lessThan(diff time.Duration, upper int) bool {
    return diff < time.Duration(upper)*time.Microsecond && diff != 0
}

func greaterThan(diff time.Duration, upper int) bool {
    return diff > time.Duration(upper)*time.Microsecond
}

但是,我对自己的做法不太满意。我不应该数数,对吧?我应该倒计时...我只是很困惑,需要帮助我应该使用什么方法。

我想要发生的事情:
1. 当certainSomething发生时,从timeDelay开始倒计时到0。
2. 在倒计时达到 0 之前,不要调用 iShouldOnlyBeCalledWhenDelayHasBeenReached
3. 这应该都发生在一个循环内,确切地说是一个服务器循环接收数据包。

我的问题:
1. 我应该怎么做才能实现这种倒计时风格?

谢谢,任何建议或示例代码都会有很大帮助。

Note: There are other functions in the loop. Doing other things. This is the main loop. I can't make it Sleep.

最佳答案

您可以设置一个 channel ,让您知道何时超过了时间。

这是一个例子 on play

它还有一个额外的好处,就是在 select 语句中,您可以有其他 channel 用于其他目的。例如,如果您在此循环中做其他工作,您也可以在 goroutine 中生成该工作并将结果发送回另一个 channel 。
然后在 timeDelay 之后或其他工作完成时退出,或者其他什么。

package main

import (
    "fmt"
    "time"
)

func main() {
    certainSomething := true // will cause time loop to repeat

    timeDelay := 900 * time.Millisecond // == 900000 * time.Microsecond

    var endTime <-chan time.Time // signal for when timer us up

    for {
        // if a certain something happens, start a timer
        if certainSomething && endTime == nil {
            endTime = time.After(timeDelay)
        }
        select {
        case <-endTime:
            fmt.Println("Yes Finally!")
            endTime = nil
        default:
            fmt.Println("not yet")
            time.Sleep(50 * time.Millisecond) // simulate work
            continue
        }

        // function shouldn't be called if the elapsed amount
        //      of time required has not yet been reached
        iShouldOnlyBeCalledWhenDelayHasBeenReached() // this could also just be moved to the <- endtime block above
    }
}

func iShouldOnlyBeCalledWhenDelayHasBeenReached() {
    fmt.Println("I've been called")
}

关于algorithm - 进入循环倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061263/

有关algorithm - 进入循环倒数计时器的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  5. ruby - Ruby 中的闭包和 for 循环 - 2

    我是Ruby的新手,有些闭包逻辑让我感到困惑。考虑这段代码:array=[]foriin(1..5)array[5,5,5,5,5]这对我来说很有意义,因为i被绑定(bind)在循环之外,所以每次循环都会捕获相同的变量。使用每个block可以解决这个问题对我来说也很有意义:array=[](1..5).each{|i|array[1,2,3,4,5]...因为现在每次通过时都单独声明i。但现在我迷路了:为什么我不能通过引入一个中间变量来修复它?array=[]foriin1..5j=iarray[5,5,5,5,5]因为j每次循环都是新的,我认为每次循环都会捕获不同的变量。例如,这绝对

  6. ruby - Ruby 性能中的计时器 - 2

    我正在寻找一个用ruby​​演示计时器的在线示例,并发现了下面的代码。它按预期工作,但这个简单的程序使用30Mo内存(如Windows任务管理器中所示)和太多CPU有意义吗?非常感谢deftime_blockstart_time=Time.nowThread.new{yield}Time.now-start_timeenddefrepeat_every(seconds)whiletruedotime_spent=time_block{yield}#Tohandle-vesleepinteravalsleep(seconds-time_spent)iftime_spent

  7. Ruby:数组中的下一个/上一个值,循环数组,数组位置 - 2

    假设我有一个没有特定顺序的随机数数组。假设这些是参加马拉松比赛的人的ID#,他们按照完成的顺序添加到数组中,例如:race1=[8,102,67,58,91,16,27]race2=[51,31,7,15,99,58,22]这是一个简化且有些做作的示例,但我认为它传达了基本思想。现在有几个问题:首先,我如何获得特定条目之前和之后的ID?假设我正在查看运行者58,我想知道谁在他之前和之后完成了比赛。race1,runner58:previousfinisher=67,nextfinisher=91race2,runner58:previousfinisher=99,nextfinishe

  8. ruby - 奇怪的 ruby​​ for 循环行为(为什么这样做有效) - 2

    defreverse(ary)result=[]forresult[0,0]inaryendresultendassert_equal["baz","bar","foo"],reverse(["foo","bar","baz"])这行得通,我想了解原因。有什么解释吗? 最佳答案 如果我使用each而不是for/in重写它,它看起来像这样:defreverse(ary)result=[]#forresult[0,0]inaryary.eachdo|item|result[0,0]=itemendresultendforainb基本上就

  9. ruby - 如何证明 Ruby `for` 循环实际上是使用 `each` 方法实现的? - 2

    在EloquentRuby(第21页,第一版,第六次打印)一书中,作者(RussOlsen)提倡使用each方法而不是for循环,这与我在其他地方读到的所有内容一致。但是作者还继续说,这样做的一个原因是for循环实际上调用了each方法,所以为什么不直接删掉中间人并使用each?所以我想知道这实际上是如何工作的。为了调查,我确实在github上的Ruby存储库上进行了搜索,但发现很难确定我在哪里/如何看到它的实际效果。重述问题:我如何证明Rubyfor循环实际上是使用each方法实现的? 最佳答案 您可以通过编写一个实现每个的类来展

  10. ruby - 循环遍历数组的元素 - 2

    我想从0到2循环@a:0,1,2,0,1,2。defset_aif@a==2@a=0else@a=@a+1endend也许有更好的方法? 最佳答案 (0..2).cycle(3){|x|putsx}#=>0,1,2,0,1,2,0,1,2item=[0,1,2].cycle.eachitem.next#=>0item.next#=>1item.next#=>2item.next#=>0... 关于ruby-循环遍历数组的元素,我们在StackOverflow上找到一个类似的问题:

随机推荐