Example #1
0
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
}
Example #2
0
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)
		}
	}

}
Example #3
0
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)
		}
	}
}
Example #4
0
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
}
Example #5
0
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")
	}
}
Example #6
0
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)
			}
		}
	}()
}
Example #7
0
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()
}
Example #8
0
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")
	}
}
Example #9
0
func main() {

	// Los temporizadores representan un evento único en
	// el futuro. Tú le dices al temporizador cuánto tiempo
	// quieres esperar, y él te proporcionará un canal que
	// será notificado en ese momento. Este temporizador
	// esperará 2 segundos.
	timer1 := time.NewTimer(time.Second * 2)

	// `<-timer1.C` bloquea el canal `C` del temporizador
	// hasta que envía un valor indicando que el
	// temporizador ha finalizado
	<-timer1.C
	fmt.Println("Temporizador 1 finalizado")

	// Si solo necesitas esperar, puedes usar
	// `time.Sleep`. Una de las razones por las que un
	// temporizador puede ser útil es que puedes
	// detenerlo antes de que finalice.
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Temporizador 2 finalizado")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Temporizador 2 detenido")
	}
}
Example #10
0
File: vfmap.go Project: ilahsa/go
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)
			}
		}
	}()
}
Example #11
0
func main() {

	// timers represent a single event in the future.
	// we tell the timer how long we want to wait, and
	// it provides a channel that will be notified at
	// that time. this timer waits 2 seconds
	timer1 := time.NewTimer(time.Second * 2)

	// this statement blocks on the timer's channel C
	// untl it sends a value indicating that the timer
	// has expired
	<-timer1.C
	fmt.Println("Timer 1 expired")

	// if we just wanted to wait, we could have just
	// used time.Sleep. One reason a timer might be useful
	// is that you can cancel the timer before it expires
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()

	// the first timer will expire ~2s after the start,
	// but the second should be stopped before it has a
	// chance to expire
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}
}
Example #12
0
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
		}
	}
}
Example #13
0
// 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()
	}()
}
Example #14
0
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
	// }
}
Example #15
0
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)
}
Example #16
0
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()))))
				}
			}
		}
	}
}
Example #17
0
File: main.go Project: aoeu/acme
// 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")
				}
			}
		}
	}
}
Example #18
0
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----------------------")
	}
}
Example #19
0
// newSocket creates a new socket and initializes it.
func newSocket(bs backend.BackendSocket) *Socket {
	// Create a new socket value.
	s := &Socket{
		bs:            bs,
		writeChan:     bs.WriteChan(),
		readChan:      bs.ReadChan(),
		finalReadChan: make(chan string, readChanBuffer),
		isClosedChan:  make(chan struct{}),

		pingTimer:   time.NewTimer(pingPeriod),
		pingTimeout: time.NewTimer(pingResponseTimeout),
	}

	// Set the event functions.
	bs.OnClose(s.onClose)

	// Stop the timeout again. It will be started by the ping timer.
	s.pingTimeout.Stop()

	// Start the loops and handlers in new goroutines.
	go s.pingTimeoutHandler()
	go s.readLoop()
	go s.pingLoop()

	return s
}
Example #20
0
// NewWithConfig creates a new raftServer.
// Parameters:
//  clusterServer : Server object of cluster API. cluster.Server provides message send
//                  receive along with other facilities such as finding peers
//  raftConfig    : Raft configuration object
func NewWithConfig(clusterServer cluster.Server, l llog.LogStore, raftConfig *RaftConfig) (raft.Raft, error) {
	s := raftServer{currentState: &utils.AtomicInt{Value: FOLLOWER}, rng: rand.New(rand.NewSource(time.Now().UnixNano()))}
	s.server = clusterServer
	s.config = raftConfig
	s.localLog = l
	s.commitIndex = &utils.AtomicI64{}
	s.lastApplied = &utils.AtomicI64{}
	s.leaderId = &utils.AtomicInt{Value: NONE}
	s.inbox = make(chan *raft.LogEntry, bufferSize)
	s.outbox = make(chan interface{}, bufferSize)
	// read persistent state from the disk if server was being restarted as a
	// part of recovery then it would find the persistent state on the disk
	s.readPersistentState()
	s.eTimeout = time.NewTimer(time.Duration(s.config.TimeoutInMillis+s.rng.Int63n(150)) * time.Millisecond) // start timer
	s.hbTimeout = time.NewTimer(time.Duration(s.config.TimeoutInMillis) * time.Millisecond)
	s.hbTimeout.Stop()
	s.state.VotedFor.Set(NotVoted)

	err := getLog(&s, raftConfig.LogDirectoryPath)
	if err != nil {
		return nil, err
	}

	go s.redeliverLogEntries()
	go s.serve()
	return raft.Raft(&s), err
}
Example #21
0
File: timers.go Project: kmagoye/go
func main() {

	// Timers represent a single event in the future. You
	// tell the timer how long you want to wait, and it
	// provides a channel that will be notified at that
	// time. This timer will wait 2 seconds.
	timer1 := time.NewTimer(time.Second * 2)

	// The `<-timer1.C` blocks on the timer's channel `C`
	// until it sends a value indicating that the timer
	// expired.
	<-timer1.C
	fmt.Println("Timer 1 expired")

	// If you just wanted to wait, you could have used
	// `time.Sleep`. One reason a timer may be useful is
	// that you can cancel the timer before it expires.
	// Here's an example of that.
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}
}
Example #22
0
func main() {
	//Timers (Used to trigger some event after certain time once in the future)
	timer1 := time.NewTimer(time.Second * 1) //Creating a timer which will send value to a channel after 1 sec

	<-timer1.C //Here it will wait on timer1's channel C to receive value and get expired
	fmt.Println("Timer 1 expired")

	timer2 := time.NewTimer(time.Second * 1) //Creating one more channel
	go func() {
		<-timer2.C //This will also wait for timer2 to get expired
		fmt.Println("Timer 2 expired")
	}()
	//We could have used Sleep for waiting but in case of timers we can stop it from waiting.
	stop2 := timer2.Stop() //Here we stopped timer2 from waiting, it will return bool true
	if stop2 {
		fmt.Println("Timer 2 stopped") //While timer2 was waiting we stopped it.
	}

	//Tickers (Used to trigger some event repeatedly at regular intervals)
	ticker := time.NewTicker(time.Second * 1) //Here we create a ticker which will send value to channel repeatedly after every 1 sec
	go func() {
		for t := range ticker.C { //This for loop will keep on receiving values from the ticker channel repeatedly after every 1 sec
			fmt.Println("Tick at", t)
		}
	}()
	time.Sleep(time.Second * 3) //Sleeping for three second and giving some time to ticker for ticking
	ticker.Stop()               //Stoping the ticker, if we won't stop than our ticker will keep ticking.
	fmt.Println("Ticker stopped")
}
Example #23
0
func (c *ClusterChecker) Start() error {
	endPollonProxyCh := make(chan error)
	checkCh := make(chan error)
	timerCh := time.NewTimer(0).C

	for true {
		select {
		case <-timerCh:
			go func() {
				checkCh <- c.Check()
			}()
		case err := <-checkCh:
			if err != nil {
				log.Debug("check reported error", zap.Error(err))
			}
			if err != nil {
				return fmt.Errorf("checker fatal error: %v", err)
			}
			timerCh = time.NewTimer(cluster.DefaultProxyCheckInterval).C
		case err := <-endPollonProxyCh:
			if err != nil {
				return fmt.Errorf("proxy error: %v", err)
			}
		}
	}
	return nil
}
Example #24
0
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")
	}
}
Example #25
0
func newRWFolder(m *Model, shortID uint64, cfg config.FolderConfiguration) *rwFolder {
	return &rwFolder{
		stateTracker: stateTracker{
			folder: cfg.ID,
			mut:    sync.NewMutex(),
		},

		model:            m,
		progressEmitter:  m.progressEmitter,
		virtualMtimeRepo: db.NewVirtualMtimeRepo(m.db, cfg.ID),

		folder:      cfg.ID,
		dir:         cfg.Path(),
		scanIntv:    time.Duration(cfg.RescanIntervalS) * time.Second,
		ignorePerms: cfg.IgnorePerms,
		copiers:     cfg.Copiers,
		pullers:     cfg.Pullers,
		shortID:     shortID,
		order:       cfg.Order,

		stop:        make(chan struct{}),
		queue:       newJobQueue(),
		pullTimer:   time.NewTimer(shortPullIntv),
		scanTimer:   time.NewTimer(time.Millisecond), // The first scan should be done immediately.
		delayScan:   make(chan time.Duration),
		scanNow:     make(chan rescanRequest),
		remoteIndex: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a notification if we're busy doing a pull when it comes.

		errorsMut: sync.NewMutex(),
	}
}
Example #26
0
func timers_() {
	/*
		Timers represent a single event in the future.
		You tell the timer how long you want to wait,
		and it provides a channel that will be notified
		at that time. This timer will wait 2 seconds.
	*/
	time1 := time.NewTimer(time.Second * 2)

	/*
		The <-timer1.C blocks on the timer is channel C
		until it sends a value indicating
		that the timer expired.
	*/
	<-time1.C
	fmt.Println("Timer 1 expired.")

	time2 := time.NewTimer(time.Second)
	go func() {
		<-time2.C
		fmt.Println("Timer 2 expired.")
	}()
	stop2 := time2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped.")
	}
}
Example #27
0
func (r *reliableResponder) Run() {
	defer r.shutdown()
	t := time.NewTimer(RESEND_MILLIS)
	for {
		select {
		case m := <-r.fromApp:
			r.doLog(m.String())
			if m.Kind == msg.SHUTDOWN {
				return
			}
			rm := &RMessage{route: APP, message: *m}
			r.writeResponse(rm)
		case rm := <-r.fromListener:
			r.doLog(rm.String())
			if rm.route == ACK {
				if rm.direction == IN {
					r.handleInAck(rm)
				} else {
					r.writeResponse(rm)
				}
			} else {
				panic(fmt.Sprintf("Illegal message received from listener: %v", rm))
			}
		case <-t.C:
			r.resend()
			t = time.NewTimer(RESEND_MILLIS)
		}
	}
}
Example #28
0
// Aggregate starts the MetricAggregator so it begins consuming metrics from MetricChan
// and flushing them periodically via its Sender
func (a *MetricAggregator) Aggregate() {
	flushChan := make(chan error)
	flushTimer := time.NewTimer(a.FlushInterval)

	for {
		select {
		case metric := <-a.MetricChan: // Incoming metrics
			a.receiveMetric(metric)
		case <-flushTimer.C: // Time to flush to graphite
			flushed := a.flush()
			go func() {
				flushChan <- a.Sender.SendMetrics(flushed)
			}()
			a.Reset()
			flushTimer = time.NewTimer(a.FlushInterval)
		case flushResult := <-flushChan:
			a.Lock()

			if flushResult != nil {
				log.Printf("Sending metrics to Graphite failed: %s", flushResult)
				a.Stats.LastFlushError = time.Now()
			} else {
				a.Stats.LastFlush = time.Now()
			}
			a.Unlock()
		}
	}

}
Example #29
0
// Creates new instance of Worker. Returns error on fail.
func NewWorker() (worker *Worker, err error) {
	sock, err := newAsyncRWSocket("unix", flagEndpoint, time.Second*5)
	if err != nil {
		return
	}

	logger, err := NewLogger()
	if err != nil {
		return
	}

	workerID, _ := uuid.FromString(flagUUID)

	disown_timeout := 5 * time.Second

	w := Worker{
		unpacker:        newStreamUnpacker(),
		uuid:            workerID,
		logger:          logger,
		heartbeat_timer: time.NewTimer(HEARTBEAT_TIMEOUT),
		disown_timer:    time.NewTimer(disown_timeout),
		sessions:        make(map[int64](*Request)),
		from_handlers:   make(chan rawMessage),
		socketIO:        sock,
		fallback:        defaultFallbackHandler,
		disown_timeout:  disown_timeout,
	}
	w.disown_timer.Stop()
	w.handshake()
	w.heartbeat()
	worker = &w
	return
}
Example #30
0
func (f *Follower) startBackGroundTimer() {
	timer := time.NewTimer(f.leaderTimeout())

	for {
		select {
		case <-f.StopCh:
			timer.Stop()
			close(f.resetTimerCh)
			return

		case <-f.resetTimerCh:
			duration := f.leaderTimeout()
			if !timer.Reset(duration) {
				timer = time.NewTimer(duration)
			}

		case <-timer.C:
			if f.Status() == common.Started {
				f.listener.HandleEvent(
					common.Event{
						Term:      f.stateStore.CurrentTerm(),
						EventType: common.LeaderKeepAliveTimeout,
					})
			}
		}
	}
}