没有营业执照 怎么做网站,开个网站做,建设一个门户网站需要多少钱,爱网卡设想一下你在接收源源不断的数据#xff0c;如果有700ms没有收到#xff0c;则认为是一个超时#xff0c;需要做出处理。
逻辑上可以设计一个grouting,里面放一个通道#xff0c;每收到一条数据进行相应处理。通道中夹杂一个timer定时器的处理#xff0c;若通道在700ms内…设想一下你在接收源源不断的数据如果有700ms没有收到则认为是一个超时需要做出处理。
逻辑上可以设计一个grouting,里面放一个通道每收到一条数据进行相应处理。通道中夹杂一个timer定时器的处理若通道在700ms内有数据则定时器被重置重新等待700ms再调用定时器处理函数否则700ms时间到运行定时器处理函数。示例代码如下
package mainimport (fmtruntime/debugstringstime
)type demoSaveSuite struct {chanDemoSave chan string
}const dbSaveWaitDuration 700 * time.Millisecondfunc (s *demoSaveSuite) DemoHandler() {go func() {defer func() {if r : recover(); r ! nil {fmt.Println(string(debug.Stack()))}}()var timer *time.Timerfor sqlEntity : range s.chanDemoSave {fmt.Printf(Received SQL entity: %s\n, sqlEntity)// 检查 sqlEntity 是否包含 SQL_Entity_5if strings.Contains(sqlEntity, SQL_Entity_5) {if timer ! nil {timer.Stop()timer nil // 将 timer 设为 nil 以确保不再使用它continue // 跳过本次循环的后续部分}}if timer nil {timer time.AfterFunc(dbSaveWaitDuration, func() {fmt.Printf(Executing action after delay for entity: %s\n, sqlEntity)})} else {timer.Reset(dbSaveWaitDuration)}}}()
}func main() {// You can place your main code here if neededsuite : demoSaveSuite{chanDemoSave: make(chan string, 5), // Buffer to avoid blocking when sending messages}go suite.DemoHandler()// Send the first SQL entitysuite.chanDemoSave - SQL_Entity_1_300Millisecondtime.Sleep(300 * time.Millisecond) // sleep a bit, but not enough for dbSaveWaitDuration// Send the second SQL entitysuite.chanDemoSave - SQL_Entity_2_800Millisecondtime.Sleep(800 * time.Millisecond) // let the timer expire for SQL_Entity_1// Send the third SQL entity to test resetting the timersuite.chanDemoSave - SQL_Entity_3_300Millisecondtime.Sleep(300 * time.Millisecond) // sleep a bit, but not enough for dbSaveWaitDuration// Send the fourth SQL entitysuite.chanDemoSave - SQL_Entity_4_800Millisecondtime.Sleep(800 * time.Millisecond) // let the timer expire for SQL_Entity_3// Send the fourth SQL entitysuite.chanDemoSave - SQL_Entity_5_2500Millisecondtime.Sleep(2500 * time.Millisecond) // let the timer expire for SQL_Entity_3// Close the channelclose(suite.chanDemoSave)
}
代码动行结果
Received SQL entity: SQL_Entity_1_300Millisecond
Received SQL entity: SQL_Entity_2_800Millisecond
Executing action after delay for entity: SQL_Entity_2_800Millisecond
Received SQL entity: SQL_Entity_3_900Millisecond
Received SQL entity: SQL_Entity_4_800Millisecond
Executing action after delay for entity: SQL_Entity_4_800Millisecond
Received SQL entity: SQL_Entity_5_2500Millisecond
Executing action after delay for entity: SQL_Entity_5_2500Millisecond从运行结果看只要超过700ms没有数据进入就会引发定时器的回调并且从2500ms的超时看只激发了一次说明这里的定时器只会运行一次。没有超过700ms的由于定时器被重置了又开始等700ms才会运行运行SQL_Entity_3时定时器被删除从结果看虽然间隔是900ms远超700ms,依然定时器没有执行。接收到SQL_Entity_4时由于timer已经为nil,因此又重新开启定时器