我现在正在学习,我很怀念来自golang的Nodejs的setTimeout。我还没有读到太多,我想知道我是否可以在go中实现同样的东西,比如一个间隔或一个回环。
有没有办法把这段代码从node写到golang?我听说golang很好地处理并发,这可能是一些goroutines或其他?
//Nodejs
function main() {
//Do something
setTimeout(main, 3000)
console.log('Server is listening to 1337')
}提前谢谢你!
//Go version
func main() {
for t := range time.Tick(3*time.Second) {
fmt.Printf("working %s \n", t)
}
//basically this will not execute..
fmt.Printf("will be called 1st")
}发布于 2014-06-06 10:09:08
最接近的等效函数是time.AfterFunc函数:
import "time"
...
time.AfterFunc(3*time.Second, somefunction)这将产生一个新的goroutine,并在指定的时间后运行给定的函数。包中还有其他可能有用的相关函数:
time.After:此版本将返回一个通道,该通道将在给定的时间量之后发送一个值。如果您想在等待一个或多个channels.time.Sleep:时超时,这与select语句结合使用会很有用,此版本将简单地阻塞,直到计时器超时。在Go中,更常见的是编写同步代码并依靠调度程序切换到其他goroutine,所以有时简单地阻塞是最好的解决方案。还有time.Timer和time.Ticker类型,可用于您可能需要取消计时器的较小情况。
发布于 2016-09-08 20:37:16
另一种解决方案可以是实现
立即调用的函数表达式(IIFE)函数如下:
go func() {
time.Sleep(time.Second * 3)
// your code here
}()发布于 2018-03-08 04:47:19
此website提供了一个涉及通道和select函数的有趣的超时示例和解释。
// _Timeouts_ are important for programs that connect to
// external resources or that otherwise need to bound
// execution time. Implementing timeouts in Go is easy and
// elegant thanks to channels and `select`.
package main
import "time"
import "fmt"
func main() {
// For our example, suppose we're executing an external
// call that returns its result on a channel `c1`
// after 2s.
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
// Here's the `select` implementing a timeout.
// `res := <-c1` awaits the result and `<-Time.After`
// awaits a value to be sent after the timeout of
// 1s. Since `select` proceeds with the first
// receive that's ready, we'll take the timeout case
// if the operation takes more than the allowed 1s.
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
// If we allow a longer timeout of 3s, then the receive
// from `c2` will succeed and we'll print the result.
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}您也可以在Go Playground上运行它
https://stackoverflow.com/questions/24072767
复制相似问题