以不同的持续时间重复倒计时

这些“功能”以相同的方式运行,实际上它们的调用方式几乎相同。该方法被称为方法表达式,接收者作为第一个参数:


var s Square


// The method call

s.SetSide(5)

// is equivalent to the method expression

(*Square).SetSide(&s, 5)

该SetSide方法也可以用作方法值来满足函数签名func(int),而SetSquareSide不能。


var f func(int)


f = a.SetSide

f(9)

这是在方法集Square满足接口的明显事实之上


interface {

    SetSide(int)

}


繁星coding
浏览 203回答 2
2回答

守着一只汪

如果你愿意,你可以打电话给 sleepdur := 1 * time.SecondnextDur := 3 * time.Secondfor {&nbsp; &nbsp; time.Sleep(dur)&nbsp; &nbsp; dur, nextDur = nextDur, dur&nbsp; &nbsp; ...}或者,time.Timer如果需要,可以交替使用 a 中的持续时间select。这是我个人会坚持的,因为您不必担心由于调度不一致而导致两个计时器之间的偏移。dur := 1 * time.SecondnextDur := 3 * time.Secondtimer := time.NewTimer(dur)for {&nbsp; &nbsp; select {&nbsp; &nbsp; case t := <-timer.C:&nbsp; &nbsp; &nbsp; &nbsp; dur, nextDur = nextDur, dur&nbsp; &nbsp; &nbsp; &nbsp; timer.Reset(dur)&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }&nbsp; &nbsp; ...}或者运行 2 个定时器以较小的间隔偏移dur1 := 1 * time.Seconddur2 := 3 * time.Secondtimer1 := time.NewTimer(dur1)timer2 := time.NewTimer(dur1 + dur2)for {&nbsp; &nbsp; select {&nbsp; &nbsp; case t := <-timer1.C:&nbsp; &nbsp; &nbsp; &nbsp; timer1.Reset(dur1 + dur2)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timer1:", t)&nbsp; &nbsp; case t := <-timer2.C:&nbsp; &nbsp; &nbsp; &nbsp; timer2.Reset(dur1 + dur2)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timer2:", t)&nbsp; &nbsp; }}你也可以像最初尝试的那样运行交错的 Tickers,但这需要更多的协调来延迟其中一个的启动dur1 := 1 * time.Seconddur2 := 3 * time.Secondticker1 := time.NewTicker(dur1)ticker2 := time.NewTicker(dur1 + dur2)var once sync.OncedelayOnce := func() {&nbsp; &nbsp; ticker1.Stop()&nbsp; &nbsp; ticker1 = time.NewTicker(dur1 + dur2)}for&nbsp; {&nbsp; &nbsp; select {&nbsp; &nbsp; case t := <-ticker1.C:&nbsp; &nbsp; &nbsp; &nbsp; once.Do(delayOnce)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("ticker1:", t)&nbsp; &nbsp; case t := <-ticker2.C:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("ticker2:", t)&nbsp; &nbsp; }}

慕尼黑8549860

一种解决方案是只有 1 个每 5 秒滴答一次的股票代码。5分钟加5秒就是61*5秒。所以“周期”是 61 个滴答声。每个61th刻度是 5 分钟标记,每个61th+1刻度是 5 秒标记。由于只有一个股票代码,因此甚至不需要select:c, count := time.Tick(5*time.Second), 1for {&nbsp; &nbsp; <-c&nbsp; &nbsp; count++&nbsp; &nbsp; switch count % 61 {&nbsp; &nbsp; case 0:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("5-min mark")&nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("5-sec mark")&nbsp; &nbsp; }}注意:由于count是用 初始化的1,第一个“任务”将是5-min mark,在启动后 5 分钟后执行。另一种解决方案是使用 2 个time.Sleep()调用的序列,第一个是 5 分钟,第二个是 5 秒:for {&nbsp; &nbsp; time.Sleep(5 * time.Minute)&nbsp; &nbsp; fmt.Println("5-min mark")&nbsp; &nbsp; time.Sleep(5 * time.Second)&nbsp; &nbsp; fmt.Println("5-sec mark")}但是这个时间也取决于你执行的任务。所以要么使用第一个解决方案,要么在单独的 goroutines 中执行任务,这样它们就不会干扰时间,例如:for {&nbsp; &nbsp; time.Sleep(5 * time.Minute)&nbsp; &nbsp; go func () {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("5-min mark")&nbsp; &nbsp; }&nbsp; &nbsp; time.Sleep(5 * time.Second)&nbsp; &nbsp; go func () {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("5-sec mark")&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go