本文整理汇总了Golang中Time.Sleep函数的典型用法代码示例。如果您正苦于以下问题:Golang Sleep函数的具体用法?Golang Sleep怎么用?Golang Sleep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sleep函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: OnMONITOR
// redis-cli对monitor指令进行特殊处理,只要monitor不断输出StatusReply,可以实现不间断的流输出
// 适用于海量数据的扫描输出,比如iterator扫描整个数据库
func (server *GoRedisServer) OnMONITOR(session *Session, cmd *Command) (reply *Reply) {
// 特殊使用,monitor输出全部key
if cmd.Len() > 1 {
switch strings.ToUpper(cmd.StringAtIndex(1)) {
case "KEYS":
server.monitorKeys(session, cmd)
default:
reply = ErrorReply("bad monitor command")
go func() {
time.Sleep(time.Millisecond * 100)
session.Close()
}()
}
return
}
session.WriteReply(StatusReply("OK"))
client := NewMonClient(session)
remoteHost := session.RemoteAddr().String()
go func() {
stdlog.Printf("[%s] monitor start\n", remoteHost)
// sleep一下,避免启动瞬间输出 +1394530022.495448 [0 127.0.0.1:51980] "monitor"
time.Sleep(time.Millisecond * 10)
server.monmgr.Put(remoteHost, client)
client.Start()
server.monmgr.Remove(remoteHost)
stdlog.Printf("[%s] monitor exit\n", remoteHost)
}()
return
}
示例2: TestPause
func TestPause(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
_, _, nsqd := mustStartNSQD(NewNSQDOptions())
defer nsqd.Exit()
topicName := "test_topic_pause" + strconv.Itoa(int(time.Now().Unix()))
topic := nsqd.GetTopic(topicName)
err := topic.Pause()
assert.Equal(t, err, nil)
channel := topic.GetChannel("ch1")
assert.NotEqual(t, channel, nil)
msg := nsq.NewMessage(<-nsqd.idChan, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa"))
err = topic.PutMessage(msg)
assert.Equal(t, err, nil)
time.Sleep(15 * time.Millisecond)
assert.Equal(t, topic.Depth(), int64(1))
assert.Equal(t, channel.Depth(), int64(0))
err = topic.UnPause()
assert.Equal(t, err, nil)
time.Sleep(15 * time.Millisecond)
assert.Equal(t, topic.Depth(), int64(0))
assert.Equal(t, channel.Depth(), int64(1))
}
示例3: configurer
func configurer(done chan bool, errLog, infoLog chan string, config chan configTask, configName string) {
var (
fd *os.File
err error
// settings settingsBlock
configBlocks []*configBlock
)
for {
select {
case <-done:
return
default:
if fd, err = os.Open(configName); err != nil {
errLog <- fmt.Sprintf("can't read configuration from %s", configName)
time.Sleep(waitForValidConfigFile)
}
_, configBlocks, err = parseConfigFile(fd)
// XXX compare with prev parsed blocks (или делать это в контроллере)
if err != nil {
errLog <- err.Error()
}
for _, b := range configBlocks {
fmt.Printf("%+v %+v\n", b, b.Checks)
}
time.Sleep(1 * time.Second)
}
}
}
示例4: TestBackToInitialFilter
func TestBackToInitialFilter(t *testing.T) {
_, guard := setDummyScreen()
defer guard()
ctx := newCtx(nil, 25)
defer ctx.Stop()
ctx.config.Keymap["C-q"] = "peco.BackToInitialFilter"
ctx.startInput()
if ctx.filters.current != 0 {
t.Errorf("Expected filter to be at position 0, got %d", ctx.filters.current)
return
}
screen.SendEvent(termbox.Event{Key: termbox.KeyCtrlR})
time.Sleep(time.Second)
if ctx.filters.current != 1 {
t.Errorf("Expected filter to be at position 1, got %d", ctx.filters.current)
return
}
screen.SendEvent(termbox.Event{Key: termbox.KeyCtrlQ})
time.Sleep(time.Second)
if ctx.filters.current != 0 {
t.Errorf("Expected filter to be at position 0, got %d", ctx.filters.current)
return
}
}
示例5: RunServerWithAuth
// New Go Routine based server with auth
func RunServerWithAuth(opts *server.Options, auth server.Auth) *server.Server {
if opts == nil {
opts = &DefaultTestOptions
}
s := server.New(opts)
if s == nil {
panic("No NATS Server object returned.")
}
if auth != nil {
s.SetAuthMethod(auth)
}
// Run server in Go routine.
go s.Start()
end := time.Now().Add(10 * time.Second)
for time.Now().Before(end) {
addr := s.Addr()
if addr == nil {
time.Sleep(50 * time.Millisecond)
// Retry. We might take a little while to open a connection.
continue
}
conn, err := net.Dial("tcp", addr.String())
if err != nil {
// Retry after 50ms
time.Sleep(50 * time.Millisecond)
continue
}
conn.Close()
return s
}
panic("Unable to start NATS Server in Go Routine")
}
示例6: EmitSignal
func (m *MonstiService) EmitSignal(args *Receive, ret *[][]byte) error {
*ret = make([][]byte, len(m.subscriptions[args.Name]))
for i, id := range m.subscriptions[args.Name] {
retChan := make(chan emitRet)
done := false
go func() {
time.Sleep(time.Second)
for !done {
time.Sleep(30 * time.Second)
m.Logger.Printf(
"Waiting for signal response. Signal: %v, Subscriber: %v",
args.Name, id)
}
}()
m.subscriber[id] <- &signal{args.Name, args.Args, retChan}
emitRet := <-retChan
if len(emitRet.Error) > 0 {
done = true
return fmt.Errorf("Received error as signal response: %v", emitRet.Error)
}
(*ret)[i] = emitRet.Ret
done = true
}
return nil
}
示例7: IsLeaderAlive
func IsLeaderAlive(currentLeader string) {
if retryCount > 0 {
fmt.Println("Trying......", retryCount)
transport := http.Transport{
Dial: dialTimeout,
}
client := http.Client{
Transport: &transport,
}
url := fmt.Sprintf("http://localhost:%s/isalive", currentLeader)
res, err := client.Get(url)
if err != nil {
time.Sleep(5000 * time.Millisecond)
retryCount--
IsLeaderAlive(currentLeader)
}
fmt.Println("Response Status:", res.StatusCode)
if res.StatusCode == 200 {
time.Sleep(5000 * time.Millisecond)
IsLeaderAlive(currentLeader)
}
} else {
resp, _ := http.Get("http://localhost:9999/flushall")
resp.Body.Close()
initiateElection()
}
}
示例8: main
func main() {
input_channel := make(chan interface{})
go func() {
for i := 0; i < 100; i++ {
// This helps reveal time-dependant bugs
time.Sleep(1000000)
input_channel <- i
}
close(input_channel)
}()
result := mapreduce.MapReduce(
func(x interface{}, output chan interface{}) {
fmt.Println("Mapping ", x)
time.Sleep(100000000)
output <- x.(int) * x.(int)
},
func(input chan interface{}, output chan interface{}) {
total := 0
for item := range input {
fmt.Println("Reducing: ", item.(int))
total += item.(int)
}
output <- total
},
input_channel, 10)
if result.(int) != 328350 {
fmt.Println(result.(int), "Unexpected MapReduce result")
} else {
fmt.Println("OK")
}
}
示例9: TestRestartContainerwithRestartPolicy
func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) {
out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")
id1 := strings.TrimSpace(string(out1))
id2 := strings.TrimSpace(string(out2))
err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second)
c.Assert(err, checker.IsNil)
// TODO: fix racey problem during restart:
// https://jenkins.dockerproject.org/job/Docker-PRs-Win2Lin/24665/console
// Error response from daemon: Cannot restart container 6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251: remove /var/run/docker/libcontainerd/6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251/rootfs: device or resource busy
if _, _, err := dockerCmdWithError("restart", id1); err != nil {
// if restart met racey problem, try again
time.Sleep(500 * time.Millisecond)
dockerCmd(c, "restart", id1)
}
if _, _, err := dockerCmdWithError("restart", id2); err != nil {
// if restart met racey problem, try again
time.Sleep(500 * time.Millisecond)
dockerCmd(c, "restart", id2)
}
dockerCmd(c, "stop", id1)
dockerCmd(c, "stop", id2)
dockerCmd(c, "start", id1)
dockerCmd(c, "start", id2)
}
示例10: initBoard
func (b *board) initBoard() {
for {
b.queryFirmware()
time.Sleep(50 * time.Millisecond)
b.readAndProcess()
if len(b.findEvents("firmware_query")) > 0 {
break
}
}
for {
b.queryCapabilities()
time.Sleep(50 * time.Millisecond)
b.readAndProcess()
if len(b.findEvents("capability_query")) > 0 {
break
}
}
for {
b.queryAnalogMapping()
time.Sleep(50 * time.Millisecond)
b.readAndProcess()
if len(b.findEvents("analog_mapping_query")) > 0 {
break
}
}
b.togglePinReporting(0, High, ReportDigital)
time.Sleep(50 * time.Millisecond)
b.togglePinReporting(1, High, ReportDigital)
time.Sleep(50 * time.Millisecond)
}
示例11: RedisDo
func RedisDo(commandName string, args ...interface{}) (interface{}, error) {
var redisConn redis.Conn
var err error
for i := 0; i < redisRetryCount; i++ {
if redisConn, err = redis.Dial("tcp", redisAddress); err != nil {
fog.Warn("redis.Dial: %s", err)
time.Sleep(5 * time.Second)
continue
}
result, err := redisConn.Do(commandName, args...)
redisConn.Close()
if err != nil {
fog.Warn("RedisDo: %s", err)
time.Sleep(1 * time.Second)
continue
}
return result, nil
}
return nil, fmt.Errorf("RedisDo: failed after %d retries %s",
redisRetryCount, err)
}
示例12: join
func join(c *cli.Context) {
dflag := getDiscovery(c)
if dflag == "" {
log.Fatalf("discovery required to join a cluster. See '%s join --help'.", c.App.Name)
}
addr := c.String("advertise")
if addr == "" {
log.Fatal("missing mandatory --advertise flag")
}
if !checkAddrFormat(addr) {
log.Fatal("--advertise should be of the form ip:port or hostname:port")
}
joinDelay, err := time.ParseDuration(c.String("delay"))
if err != nil {
log.Fatalf("invalid --delay: %v", err)
}
if joinDelay < time.Duration(0)*time.Second {
log.Fatalf("--delay should not be a negative number")
}
hb, err := time.ParseDuration(c.String("heartbeat"))
if err != nil {
log.Fatalf("invalid --heartbeat: %v", err)
}
if hb < 1*time.Second {
log.Fatal("--heartbeat should be at least one second")
}
ttl, err := time.ParseDuration(c.String("ttl"))
if err != nil {
log.Fatalf("invalid --ttl: %v", err)
}
if ttl <= hb {
log.Fatal("--ttl must be strictly superior to the heartbeat value")
}
d, err := discovery.New(dflag, hb, ttl, getDiscoveryOpt(c))
if err != nil {
log.Fatal(err)
}
// if joinDelay is 0, no delay will be executed
// if joinDelay is larger than 0,
// add a random delay between 0s and joinDelay at start to avoid synchronized registration
if joinDelay > 0 {
r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
delay := time.Duration(r.Int63n(int64(joinDelay)))
log.Infof("Add a random delay %s to avoid synchronized registration", delay)
time.Sleep(delay)
}
for {
log.WithFields(log.Fields{"addr": addr, "discovery": dflag}).Infof("Registering on the discovery service every %s...", hb)
if err := d.Register(addr); err != nil {
log.Error(err)
}
time.Sleep(hb)
}
}
示例13: readResponses
func (self *ProtobufClient) readResponses() {
message := make([]byte, 0, MAX_RESPONSE_SIZE)
buff := bytes.NewBuffer(message)
for !self.stopped {
buff.Reset()
conn := self.getConnection()
if conn == nil {
time.Sleep(200 * time.Millisecond)
continue
}
var messageSizeU uint32
var err error
err = binary.Read(conn, binary.LittleEndian, &messageSizeU)
if err != nil {
log.Error("Error while reading messsage size: %d", err)
time.Sleep(200 * time.Millisecond)
continue
}
messageSize := int64(messageSizeU)
messageReader := io.LimitReader(conn, messageSize)
_, err = io.Copy(buff, messageReader)
if err != nil {
log.Error("Error while reading message: %d", err)
time.Sleep(200 * time.Millisecond)
continue
}
response, err := protocol.DecodeResponse(buff)
if err != nil {
log.Error("error unmarshaling response: %s", err)
time.Sleep(200 * time.Millisecond)
} else {
self.sendResponse(response)
}
}
}
示例14: main
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Printf("%d, %d\n", i, <-c) // ここで読み出すと、case c <- x が評価され、fibonacci内のloopが回る
}
quit <- 0
}()
fibonacci(c, quit)
tick := time.Tick(100 * time.Millisecond)
boom := time.After(500 * time.Millisecond)
for {
select {
case <-tick:
fmt.Println("tick.")
case <-boom:
fmt.Println("BOOM!")
return
default:
fmt.Println(" .")
time.Sleep(50 * time.Millisecond)
}
}
}
示例15: waitInspect
// waitInspect will wait for the specified container to have the specified string
// in the inspect output. It will wait until the specified timeout (in seconds)
// is reached.
func waitInspect(name, expr, expected string, timeout time.Duration) error {
after := time.After(timeout)
for {
cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
out, _, err := runCommandWithOutput(cmd)
if err != nil {
if !strings.Contains(out, "No such") {
return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
}
select {
case <-after:
return err
default:
time.Sleep(10 * time.Millisecond)
continue
}
}
out = strings.TrimSpace(out)
if out == expected {
break
}
select {
case <-after:
return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
default:
}
time.Sleep(100 * time.Millisecond)
}
return nil
}