当前位置: 首页>>代码示例>>Golang>>正文


Golang Time.NewTimer函数代码示例

本文整理汇总了Golang中Time.NewTimer函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTimer函数的具体用法?Golang NewTimer怎么用?Golang NewTimer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewTimer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Run

func (t *SimpleTimer) Run() error {
	if t.j.Status == common.STATUS_FAILED || t.j.Status == common.STATUS_DONE {
		return errors.New("Cannot start task as its status is " + t.j.Status)
	}

	if t.j.Status == common.STATUS_RUNNING {
		return nil
	}

	if t.j.Status == common.STATUS_PAUSED {
		// Subtrack the time already run (r) from the set timer duration (d)
		t.t = time.NewTimer(t.d - t.r)
		t.j.Status = common.STATUS_RUNNING
	}

	t.t = time.NewTimer(t.d)
	t.s = time.Now()
	t.j.StartTime = t.s
	t.j.Status = common.STATUS_RUNNING
	t.kill = make(chan bool)

	go func() {
		select {
		case <-t.t.C:
			t.j.Status = common.STATUS_DONE
		case <-t.kill:
			return
		}
	}()

	return nil
}
开发者ID:roo7break,项目名称:cracklord,代码行数:32,代码来源:simple_timer_test.go

示例2: RunScheduleFollower

func RunScheduleFollower(schedule RunSchedule, name string, wg *sync.WaitGroup) {
	defer wg.Done()

	online := false
	scheduleIndex := 0
	start := time.Now()
	timer := time.NewTimer(schedule[scheduleIndex].start)

	for {
		select {
		case <-timer.C:
			// timer went off, transition modes
			timeOffset := time.Since(start)
			if online {
				online = false
				scheduleIndex++
				if scheduleIndex < len(schedule) {
					timer = time.NewTimer(schedule[scheduleIndex].start - timeOffset)
				}
			} else {
				online = true
				if schedule[scheduleIndex].end != -1 {
					timer = time.NewTimer(schedule[scheduleIndex].end - timeOffset)
				}
			}
		default:
			//log.Printf("client %s, online: %v", name, online)
			time.Sleep(500 * time.Millisecond)
		}
	}

}
开发者ID:ajres,项目名称:gateload,代码行数:32,代码来源:workload.go

示例3: XSIresubscribe

func XSIresubscribe(Config ConfigT, cCh chan net.Conn, owner string, Event []string, CCID string, CCEvent string) {
	exp, _ := strconv.Atoi(Config.Main.Expires)
	timer := time.NewTimer(time.Nanosecond)
	timer2 := time.NewTimer(time.Second)
	var lchanID string
	var nilchannel, lchannel net.Conn
	var def DefHead
	for {
		select {
		case <-timer.C:
			cCh <- nilchannel
			if lchannel != nil {
				lchannel.Close()
			}
			def = MakeDef(Config)
			channel, chanID := XSISubscribeCH(Config, def)
			lchannel = channel
			lchanID = chanID
			for _, event := range Event {
				XSISubscribe(Config, def, owner, event)
				cCh <- channel
				time.Sleep(time.Millisecond * 100)
			}
			XSISubscribe(Config, def, CCID, CCEvent)
			timer.Reset(time.Second * time.Duration(exp))
			timer2.Reset(time.Second * 6)
		case <-timer2.C:
			res := XSIheartbeat(Config, def, lchanID)
			if res > 0 {
				timer.Reset(time.Nanosecond)
			}
			timer2.Reset(time.Second * 6)
		}
	}
}
开发者ID:fffilimonov,项目名称:XSI_go,代码行数:35,代码来源:XSI.go

示例4: NewEndpoint

func NewEndpoint(cfg *Config) *ProxyServer {
	proxy := &ProxyServer{config: cfg, blockStats: make(map[int64]float64)}

	proxy.upstreams = make([]*rpc.RPCClient, len(cfg.Upstream))
	for i, v := range cfg.Upstream {
		client, err := rpc.NewRPCClient(v.Name, v.Url, v.Username, v.Password, v.Timeout, v.Pool)
		if err != nil {
			log.Fatal(err)
		} else {
			proxy.upstreams[i] = client
			log.Printf("Upstream: %s => %s", v.Name, v.Url)
		}
	}
	log.Printf("Default upstream: %s => %s", proxy.rpc().Name, proxy.rpc().Url)

	proxy.miners = NewMinersMap()

	timeout, _ := time.ParseDuration(cfg.Proxy.ClientTimeout)
	proxy.timeout = timeout

	hashrateWindow, _ := time.ParseDuration(cfg.Proxy.HashrateWindow)
	proxy.hashrateWindow = hashrateWindow

	luckWindow, _ := time.ParseDuration(cfg.Proxy.LuckWindow)
	proxy.luckWindow = int64(luckWindow / time.Millisecond)
	luckLargeWindow, _ := time.ParseDuration(cfg.Proxy.LargeLuckWindow)
	proxy.luckLargeWindow = int64(luckLargeWindow / time.Millisecond)

	proxy.blockTemplate.Store(&BlockTemplate{})
	proxy.fetchBlockTemplate()

	refreshIntv, _ := time.ParseDuration(cfg.Proxy.BlockRefreshInterval)
	refreshTimer := time.NewTimer(refreshIntv)
	log.Printf("Set block refresh every %v", refreshIntv)

	checkIntv, _ := time.ParseDuration(cfg.UpstreamCheckInterval)
	checkTimer := time.NewTimer(checkIntv)

	go func() {
		for {
			select {
			case <-refreshTimer.C:
				proxy.fetchBlockTemplate()
				refreshTimer.Reset(refreshIntv)
			}
		}
	}()

	go func() {
		for {
			select {
			case <-checkTimer.C:
				proxy.checkUpstreams()
				checkTimer.Reset(checkIntv)
			}
		}
	}()

	return proxy
}
开发者ID:bitbandi,项目名称:decred-proxy,代码行数:60,代码来源:proxy.go

示例5: main

func main() {

	// 定时器表示在未来某一时刻的独立事件。你告诉定时器
	// 需要等待的时间,然后它将提供一个用于通知的通道。
	// 这里的定时器将等待 2 秒。
	timer1 := time.NewTimer(time.Second * 2)

	// `<-timer1.C` 直到这个定时器的通道 `C` 明确的发送了
	// 定时器失效的值之前,将一直阻塞。
	<-timer1.C
	fmt.Println("Timer 1 expired")

	// 如果你需要的仅仅是单纯的等待,你需要使用 `time.Sleep`。
	// 定时器是有用原因之一就是你可以在定时器失效之前,取消这个
	// 定时器。这是一个例子
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}
}
开发者ID:ohlinux,项目名称:golang-snippet-cn,代码行数:25,代码来源:timers.go

示例6: start

func (k *keepAlive) start() {
	k.Lock()
	defer k.Unlock()

	if k.notifyStop != nil {
		return
	}

	// This channel must be closed to terminate idle timer.
	k.notifyStop = make(chan struct{})
	k.notifyWaitGroup.Add(1)

	go func() {
		defer k.notifyWaitGroup.Done()

		for t := time.NewTimer(k.idleTime); ; {
			select {
			case <-k.notifyStop:
				return
			case <-k.notifyRequest:
				t.Reset(k.idleTime)
			case <-t.C:
				k.keepAlive(k.roundTripper)
				t = time.NewTimer(k.idleTime)
			}
		}
	}()
}
开发者ID:kristinn,项目名称:govmomi,代码行数:28,代码来源:keep_alive.go

示例7: main

func main() {

	a, _ := strconv.Atoi(os.Args[1])
	server := Raft.New(a /* config file */, os.Args[2], os.Args[3], os.Args[4])

	wg := new(sync.WaitGroup)
	wg.Add(1)

	go func() {
		ClientTimer := time.NewTimer(time.Second)
		for {
			select {
			case <-ClientTimer.C:
				if server.State() == Raft.LEADER {
					key := strconv.Itoa(rand.Intn(100000))
					value := strconv.Itoa(rand.Intn(100000))
					server.Inbox() <- "set " + key + " " + value
				}
				ClientTimer = time.NewTimer(100 * time.Millisecond)
			}
		}
	}()

	wg.Wait()
}
开发者ID:vibhor1403,项目名称:KVStore,代码行数:25,代码来源:KVStore.go

示例8: init

func init() {
	go func() {
		t1 := time.NewTimer(time.Second * 60)
		t2 := time.NewTimer(time.Second * 90)
		for {
			select {
			case <-t1.C:
				nowUnix := time.Now().Unix()
				for k, v := range VFMapInstance.innerMap {
					//p 端超时
					if v.PPutUnix+900 < nowUnix {
						ULogger.Info("%s file timeout", v.Id)
						delete(VFMapInstance.innerMap, k)
						if v.P != nil && v.P.IsClosed() {
							v.P.Close()
						}
					}
					//被c 端获取且超时
					if v.Status == 2 && (v.CGetUnix+300) < nowUnix {
						ULogger.Info("%s recycle", v.Id)
						VFMapInstance.Update("recycle", v)
						delete(VFMapInstance.innerMap, k)
						vf := &VerifyObj{Id: getId(), P: v.P, C: nil, FileId: v.FileId, File: v.File, Status: 1, Result: "0", Seq: v.Seq, PPutUnix: v.PPutUnix}
						QueueInstance.Enqueue(vf)
						VFMapInstance.Put(vf)
						ULogger.Infof("recycle putfile 进队列 %v\n", vf)
						putFile(v.P, map[string]string{"file": v.File, "seq": v.Seq, "action": "putfile"})
					}
				}
				t1.Reset(time.Second * 60)
			case <-t2.C:
				//fmt.Println("ss")
				stat := map[string]string{"action": "stat"}
				//TCServer.
				for k, v := range VFMapInstance.c_sessions {
					if v == nil || v.State == nil {
						delete(VFMapInstance.c_sessions, k)
					}
					u := v.State.(*User)
					query := `select count(*) from exam where c_userid=? and c_getfile_time > ? and answer is not null`
					//c端回答的问题总数
					canswer := QueryInt(query, u.Id, u.WorkTime)
					query1 := `select count(*) from exam where c_userid=? and c_getfile_time > ? and answer is not null and answer_result=1`
					canswerrigth := QueryInt(query1, u.Id, u.WorkTime)
					waitcount := QueueInstance.len()
					clientcount := len(VFMapInstance.c_sessions)

					stat["finishcount"] = strconv.Itoa(canswer)
					stat["rightcount"] = strconv.Itoa(canswerrigth)
					stat["waitcount"] = strconv.Itoa(waitcount)
					stat["clientcount"] = strconv.Itoa(clientcount)
					by, _ := json.Marshal(stat)
					v.Send(link.Bytes(by))
					ULogger.Info("send to client", v.Conn().RemoteAddr().String(), "say:", string(by))
				}
				t2.Reset(time.Second * 90)
			}
		}
	}()
}
开发者ID:ilahsa,项目名称:go,代码行数:60,代码来源:vfmap.go

示例9: Start

func (s *Sentinel) Start() {
	endCh := make(chan struct{})

	ctx, cancel := context.WithCancel(context.Background())
	timerCh := time.NewTimer(0).C

	go s.electionLoop()

	for true {
		select {
		case <-s.stop:
			log.Debug("stopping stolon sentinel")
			cancel()
			s.candidate.Stop()
			s.end <- true
			return
		case <-timerCh:
			go func() {
				s.clusterSentinelCheck(ctx)
				endCh <- struct{}{}
			}()
		case <-endCh:
			timerCh = time.NewTimer(s.sleepInterval).C
		}
	}
}
开发者ID:sgotti,项目名称:stolon,代码行数:26,代码来源:sentinel.go

示例10: Start

// Starts processing a given task using given strategy with this worker.
// Call to this method blocks until the task is done or timed out.
func (w *Worker) Start(task *Task, strategy WorkerStrategy) {
	task.Callee = w
	go func() {
		shouldStop := false
		resultChannel := make(chan WorkerResult)
		go func() {
			result := strategy(w, task.Msg, task.Id())
			for !shouldStop {
				timeout := time.NewTimer(5 * time.Second)
				select {
				case resultChannel <- result:
					timeout.Stop()
					return
				case <-timeout.C:
				}
			}
		}()
		timeout := time.NewTimer(w.TaskTimeout)
		select {
		case result := <-resultChannel:
			{
				w.OutputChannel <- result
			}
		case <-timeout.C:
			{
				shouldStop = true
				w.OutputChannel <- &TimedOutResult{task.Id()}
			}
		}
		timeout.Stop()
	}()
}
开发者ID:echupriyanov,项目名称:go_kafka_client,代码行数:34,代码来源:workers.go

示例11: Ttimer

func Ttimer() {
	done := make(chan bool, 2)

	// 代表在将来发生的单一事件,需要设定等待时间
	// <The <-timer1.C blocks on the timer’s channel C
	// until it sends a value indicating that the timer expired.
	timer1 := time.NewTimer(time.Second * 4)

	go func() {
		<-timer1.C
		P("timer1 expired")
		done <- true
	}()
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		P("timer2 expired")
		done <- true
	}()

	//you can cancel the timer before it expires.
	if stop2 := timer2.Stop(); stop2 {
		P("timer2 stopped")
	}

	// for i := 0; i < 2; i++ {
	<-done
	// }
}
开发者ID:zykzhang,项目名称:practice,代码行数:29,代码来源:time.go

示例12: ensureTimerSetup

func (o *Overlord) ensureTimerSetup() {
	o.ensureLock.Lock()
	defer o.ensureLock.Unlock()
	o.ensureTimer = time.NewTimer(ensureInterval)
	o.ensureNext = time.Now().Add(ensureInterval)
	o.pruneTimer = time.NewTimer(pruneInterval)
}
开发者ID:dholbach,项目名称:snappy,代码行数:7,代码来源:overlord.go

示例13: main

func main() {
	flag.Parse()

	spawnAgents := true
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGUSR1)

	// start timer at 1 milli so we launch an agent right away
	timer := time.NewTimer(1 * time.Millisecond)

	curID := 0

	log.Printf("master: pid %d\n", os.Getpid())

	for {
		select {
		case <-sigChan:
			spawnAgents = !spawnAgents
			log.Printf("master: spawn_agents=%t\n", spawnAgents)
		case <-timer.C:
			if curID < agents {
				if spawnAgents {
					go launchAgent(curID, metrics, flushInterval, carbon, prefix)
					log.Printf("agent %d: launched\n", curID)
					curID++

					timer = time.NewTimer(spawnInterval + (time.Duration(rand.Int63n(jitter.Nanoseconds()))))
				}
			}
		}
	}
}
开发者ID:dalmatinerdb,项目名称:haggar,代码行数:32,代码来源:main.go

示例14: handleConnection

// HandleConnection handles events while
// connected to a server.
func handleConnection() {
	t := time.NewTimer(pingTime)

	defer func() {
		t.Stop()
		close(client.Out)
		serverWin.WriteString("Disconnected")
		serverWin.Ctl("clean")
		for _, w := range wins {
			w.WriteString("Disconnected")
			w.users = make(map[string]*user)
			w.lastSpeaker = ""
			w.Ctl("clean")
		}
		for err := range client.Errors {
			if err != io.EOF {
				log.Println(err)
			}
		}
	}()

	if *join != "" {
		client.Out <- irc.Msg{Cmd: irc.JOIN, Args: []string{*join}}
		*join = ""
	}

	for {
		select {
		case ev := <-winEvents:
			if ev.timeStamp {
				ev.win.printTimeStamp()
			} else {
				handleWindowEvent(ev)
			}

		case msg, ok := <-client.In:
			if !ok { // disconnect
				return
			}
			t.Reset(pingTime)
			handleMsg(msg)

		case <-t.C:
			client.Out <- irc.Msg{Cmd: irc.PING, Args: []string{client.Server}}
			t = time.NewTimer(pingTime)

		case err, ok := <-client.Errors:
			if ok {
				long, il := err.(irc.MsgTooLong)
				if !il && err != io.EOF {
					log.Println(err)
					return
				}
				if il {
					log.Println("Truncated", long.NTrunc, "bytes from message")
				}
			}
		}
	}
}
开发者ID:aoeu,项目名称:acme,代码行数:62,代码来源:main.go

示例15: ClearData

func ClearData() {
	for {
		fmt.Println("----------Start ClearData----------------------")
		location, _ := time.LoadLocation("Asia/Colombo")
		fmt.Println("location:: " + location.String())

		localtime := time.Now().Local()
		fmt.Println("localtime:: " + localtime.String())

		tmNow := time.Now().In(location)
		fmt.Println("tmNow:: " + tmNow.String())

		clerTime := time.Date(tmNow.Year(), tmNow.Month(), tmNow.Day(), 23, 59, 59, 0, location)
		fmt.Println("Next Clear Time:: " + clerTime.String())

		timeToWait := clerTime.Sub(tmNow)
		fmt.Println("timeToWait:: " + timeToWait.String())

		timer := time.NewTimer(timeToWait)
		<-timer.C
		OnSetDailySummary(clerTime)
		OnSetDailyThesholdBreakDown(clerTime)
		OnReset()

		fmt.Println("----------ClearData Wait after reset----------------------")
		timer2 := time.NewTimer(time.Duration(time.Minute * 5))
		<-timer2.C
		fmt.Println("----------End ClearData Wait after reset----------------------")
	}
}
开发者ID:DuoSoftware,项目名称:DVP-DashBoard,代码行数:30,代码来源:main.go


注:本文中的Time.NewTimer函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。