本文整理汇总了Golang中Time.Timer类的典型用法代码示例。如果您正苦于以下问题:Golang Timer类的具体用法?Golang Timer怎么用?Golang Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Stop
func (p *Process) Stop() {
p.lock.Lock()
p.stopped = true
if proc := p.process; proc != nil {
var timer *time.Timer
p.shutdown()
if p.stopTime > 0 {
timer = time.AfterFunc(p.stopTime, func() {
p.logger.Printf("Graceful shutdown timed out")
p.lock.Lock()
p.kill()
p.lock.Unlock()
})
}
p.lock.Unlock()
p.waiter.Wait()
p.lock.Lock()
if timer != nil {
timer.Stop()
}
}
p.process = nil
p.lock.Unlock()
}
示例2: resetTimer
// Reset a timer - Doesn't work properly < go 1.1
//
// This is quite hard to do properly under go < 1.1 so we do a crude
// approximation and hope that everyone upgrades to go 1.1 quickly
func resetTimer(t *time.Timer, d time.Duration) {
t.Stop()
// Very likely this doesn't actually work if we are already
// selecting on t.C. However we've stopped the original timer
// so won't break transfers but may not time them out :-(
*t = *time.NewTimer(d)
}
示例3: Dequeue
// Dequeue is used to perform a blocking dequeue
func (b *EvalBroker) Dequeue(schedulers []string, timeout time.Duration) (*structs.Evaluation, string, error) {
var timeoutTimer *time.Timer
var timeoutCh <-chan time.Time
SCAN:
// Scan for work
eval, token, err := b.scanForSchedulers(schedulers)
if err != nil {
if timeoutTimer != nil {
timeoutTimer.Stop()
}
return nil, "", err
}
// Check if we have something
if eval != nil {
if timeoutTimer != nil {
timeoutTimer.Stop()
}
return eval, token, nil
}
// Setup the timeout channel the first time around
if timeoutTimer == nil && timeout != 0 {
timeoutTimer = time.NewTimer(timeout)
timeoutCh = timeoutTimer.C
}
// Block until we get work
scan := b.waitForSchedulers(schedulers, timeoutCh)
if scan {
goto SCAN
}
return nil, "", nil
}
示例4: watchSerial
// watchSerial monitors for a change in a specific serial number. It returns
// the new serial number when it changes. If the serial number has not
// changed in the given duration then the old value is returned. A poll
// can be done by supplying 0 for the expiration.
func (m *Manager) watchSerial(old int64, src *int64, expire time.Duration) int64 {
expired := false
cv := sync.NewCond(&m.mx)
var timer *time.Timer
var rv int64
// Schedule timeout
if expire > 0 {
timer = time.AfterFunc(expire, func() {
m.lock()
expired = true
cv.Broadcast()
m.unlock()
})
} else {
expired = true
}
m.lock()
m.cvs[cv] = true
for {
rv = *src
if rv != old || expired {
break
}
cv.Wait()
}
delete(m.cvs, cv)
m.unlock()
if timer != nil {
timer.Stop()
}
return rv
}
示例5: established
func (h *FSMHandler) established() bgp.FSMState {
fsm := h.fsm
h.conn = fsm.conn
h.t.Go(h.sendMessageloop)
h.msgCh = h.incoming
h.t.Go(h.recvMessageloop)
var holdTimer *time.Timer
if fsm.negotiatedHoldTime == 0 {
holdTimer = &time.Timer{}
} else {
holdTimer = time.NewTimer(time.Second * time.Duration(fsm.negotiatedHoldTime))
}
for {
select {
case <-h.t.Dying():
return 0
case conn, ok := <-fsm.connCh:
if !ok {
break
}
conn.Close()
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": fsm.peerConfig.NeighborAddress,
}).Warn("Closed an accepted connection")
case <-h.errorCh:
h.conn.Close()
h.t.Kill(nil)
h.reason = "Peer closed the session"
return bgp.BGP_FSM_IDLE
case <-holdTimer.C:
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": fsm.peerConfig.NeighborAddress,
"data": bgp.BGP_FSM_ESTABLISHED,
}).Warn("hold timer expired")
m := bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_HOLD_TIMER_EXPIRED, 0, nil)
h.outgoing <- m
h.reason = "HoldTimer expired"
return bgp.BGP_FSM_IDLE
case <-h.holdTimerResetCh:
if fsm.negotiatedHoldTime != 0 {
holdTimer.Reset(time.Second * time.Duration(fsm.negotiatedHoldTime))
}
case s := <-fsm.adminStateCh:
err := h.changeAdminState(s)
if err == nil {
switch s {
case ADMIN_STATE_DOWN:
m := bgp.NewBGPNotificationMessage(
bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN, nil)
h.outgoing <- m
}
}
}
}
return 0
}
示例6: doLater
// execute some action in the context of the current process. Actions
// executed via this func are to be executed in a concurrency-safe manner:
// no two actions should execute at the same time. invocations of this func
// should not block for very long, unless the action backlog is full or the
// process is terminating.
// returns errProcessTerminated if the process already ended.
func (self *procImpl) doLater(deferredAction Action) (err <-chan error) {
a := Action(func() {
self.wg.Add(1)
defer self.wg.Done()
deferredAction()
})
scheduled := false
self.writeLock.Lock()
defer self.writeLock.Unlock()
var timer *time.Timer
for err == nil && !scheduled {
switch s := self.state.get(); s {
case stateRunning:
select {
case self.backlog <- a:
scheduled = true
default:
if timer == nil {
timer = time.AfterFunc(self.maxRescheduleWait, self.changed.Broadcast)
} else {
timer.Reset(self.maxRescheduleWait)
}
self.changed.Wait()
timer.Stop()
}
case stateTerminal:
err = ErrorChan(errProcessTerminated)
default:
err = ErrorChan(errIllegalState)
}
}
return
}
示例7: process_action
func process_action(ac chan action, sv *server) {
var a action
var timer *time.Timer
ch := make(chan bool, 2)
defer func() {
if timer != nil {
timer.Stop()
}
sv.lock.Lock()
delete(sv.kt, a.key)
close(ac)
sv.lock.Unlock()
close(ch)
}()
for {
select {
case a = <-ac:
if timer != nil {
timer.Stop()
}
timer = time.AfterFunc(a.exptime, func() {
sv.s.db.Delete([]byte(a.key), sv.s.wo)
ch <- true
})
case <-ch:
relog.Info("delete successed")
return
}
}
}
示例8: internalPubAsync
func internalPubAsync(clientTimer *time.Timer, msgBody *bytes.Buffer, topic *nsqd.Topic) error {
if topic.Exiting() {
return nsqd.ErrExiting
}
info := &nsqd.PubInfo{
Done: make(chan struct{}),
MsgBody: msgBody,
StartPub: time.Now(),
}
if clientTimer == nil {
clientTimer = time.NewTimer(time.Second * 5)
} else {
clientTimer.Reset(time.Second * 5)
}
select {
case topic.GetWaitChan() <- info:
default:
select {
case topic.GetWaitChan() <- info:
case <-topic.QuitChan():
nsqd.NsqLogger().Infof("topic %v put messages failed at exiting", topic.GetFullName())
return nsqd.ErrExiting
case <-clientTimer.C:
nsqd.NsqLogger().Infof("topic %v put messages timeout ", topic.GetFullName())
return ErrPubToWaitTimeout
}
}
<-info.Done
return info.Err
}
示例9: fillBatch
// fillBatch coalesces individual log lines into batches. Delivery of the
// batch happens on timeout after at least one message is received
// or when the batch is full.
func (batcher *Batcher) fillBatch(batch *Batch) (chanOpen bool) {
timeout := new(time.Timer) // Gives us a nil channel and no timeout to start with
chanOpen = true // Assume the channel is open
for {
select {
case <-timeout.C:
return !chanOpen
case line, chanOpen := <-batcher.inLogs:
if !chanOpen {
return !chanOpen
}
// We have a line now, so set a timeout
if timeout.C == nil {
defer func(t time.Time) { batcher.stats <- NewNamedValue("batch.fill.time", time.Since(t).Seconds()) }(time.Now())
timeout = time.NewTimer(batcher.timeout)
defer timeout.Stop() // ensure timer is stopped when done
}
batch.Write(line)
if batch.Full() {
return !chanOpen
}
}
}
}
示例10: clone
func (r repository) clone(schema string) error {
cmd := exec.Command(
"git",
"clone",
"--depth=1",
"-b", r.params.version,
r.cloneURL(schema),
)
cmd.Dir = r.dir
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Start()
if err != nil {
r.logger.WithFields(log.Fields{"command": cmd.Path, "args": cmd.Args, "stdout": stdout.String(), "stderr": stderr.String()}).Warnf("git clone error: %v", err)
return err
}
// kill process if token is invalid (wait password)
var timer *time.Timer
timer = time.AfterFunc(30*time.Second, func() {
cmd.Process.Kill()
})
err = cmd.Wait()
if err != nil {
r.logger.WithFields(log.Fields{"command": cmd.Path, "args": cmd.Args, "stdout": stdout.String(), "stderr": stderr.String()}).Warnf("git clone error: %v", err)
return err
}
timer.Stop()
r.logger.WithFields(log.Fields{"command": cmd.Path, "args": cmd.Args, "stdout": stdout.String(), "stderr": stderr.String()}).Info("git clone successfully")
return err
}
示例11: main
func main() {
broker := NewBroker()
port, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
if len(os.Args) > 2 {
registryURL := os.Args[2]
myURL := os.Args[3]
err := announceBroker(registryURL, myURL)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var timer *time.Timer
timer = time.AfterFunc(RegistryAnnouncePeriod, func() {
err := announceBroker(registryURL, myURL)
if err != nil {
fmt.Println("Error reannouncing to broker!")
}
timer.Reset(RegistryAnnouncePeriod)
})
}
http.Handle("/", broker)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
示例12: listRemote
func (r repository) listRemote() error {
cmd := exec.Command(
"git",
"ls-remote",
r.cloneURL("https"),
"HEAD",
)
cmd.Dir = r.dir
err := cmd.Start()
if err != nil {
return err
}
// kill process if token is invalid (wait password)
var timer *time.Timer
timer = time.AfterFunc(5*time.Second, func() {
cmd.Process.Kill()
})
err = cmd.Wait()
if err != nil {
return err
}
timer.Stop()
return err
}
示例13: Read
// Read is used to read from the stream
func (s *Stream) Read(b []byte) (n int, err error) {
var bufsiz int
defer asyncNotify(s.recvNotifyCh)
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamRemoteClose:
fallthrough
case streamClosed:
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
s.stateLock.Unlock()
return 0, io.EOF
}
s.recvLock.Unlock()
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
goto WAIT
}
// Read any bytes
n, _ = s.recvBuf.Read(b)
bufsiz = s.recvBuf.Len()
s.recvLock.Unlock()
// Send a window update potentially
if uint32(bufsiz)+atomic.LoadUint32(&s.recvWindow) < s.session.config.MaxStreamWindowSize {
err = s.sendWindowUpdate()
}
return n, err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
if !s.readDeadline.IsZero() {
delay := s.readDeadline.Sub(time.Now())
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.recvNotifyCh:
if timer != nil {
timer.Stop()
}
goto START
case <-timeout:
return 0, ErrTimeout
}
}
示例14: process
func process(cmd *Command) {
var timer *time.Timer
var err error
log.Print(cmd.Command)
sp := exec.Command("sh", "-c", cmd.Command)
sp.Stdout = os.Stdout
sp.Stderr = os.Stderr
if err = sp.Start(); err != nil {
log.Printf("%s failed: %s", err.Error(), cmd.Command)
return
}
if cmd.Timeout > 0 {
timer = time.AfterFunc(time.Duration(cmd.Timeout)*time.Second, func() {
timer = nil
if sp.ProcessState == nil {
sp.Process.Kill()
}
})
}
err = sp.Wait()
if timer != nil {
timer.Stop()
}
if err != nil {
log.Printf("%s failed: %s", err.Error(), cmd.Command)
}
}
示例15: runReader
func (s *Scheme) runReader(reader factory.Reader, timer *time.Timer) {
if s.warmupMessagesPerRun > 0 {
logs.Logger.Info("Reading %d warmup messages", s.warmupMessagesPerRun)
}
var startTime, lastMessageTime time.Time
buffer := make([]byte, s.bytesPerMessage*2)
for i := 0; i < s.warmupMessagesPerRun; i++ {
reader.Read(buffer)
}
logs.Logger.Info("Starting reading %d messages...", s.messagesPerRun)
for {
count, err := reader.Read(buffer)
if err == io.EOF {
break
}
lastMessageTime = time.Now()
if startTime.IsZero() {
startTime = lastMessageTime
}
timer.Reset(s.waitForLastMessage)
s.countMessage(count, err)
}
logs.Logger.Info("Finished.")
s.runTime = lastMessageTime.Sub(startTime)
}