本文整理汇总了Golang中Time.Timer.Stop方法的典型用法代码示例。如果您正苦于以下问题:Golang Timer.Stop方法的具体用法?Golang Timer.Stop怎么用?Golang Timer.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Timer
的用法示例。
在下文中一共展示了Timer.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
示例2: Watch
func (log *Log) Watch(last int64, expire time.Duration) int64 {
expired := false
var timer *time.Timer
cv := sync.NewCond(&log.mx)
if expire > 0 {
timer = time.AfterFunc(expire, func() {
log.lock()
expired = true
cv.Broadcast()
log.unlock()
})
} else {
expired = true
}
log.lock()
log.cvs[cv] = true
for {
if log.id != last || expired {
break
}
cv.Wait()
}
delete(log.cvs, cv)
if log.id != last {
last = log.id
}
log.unlock()
if timer != nil {
timer.Stop()
}
return last
}
示例3: 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
}
示例4: 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.
// returns the channel status, completed batch
func (b Batcher) fillBatch() (bool, Batch) {
batch := NewBatch(b.batchSize)
timeout := new(time.Timer) // start with a nil channel and no timeout
for {
select {
case <-timeout.C:
return false, batch
case line, chanOpen := <-b.inLogs:
// if the channel is closed, then line will be a zero value Line, so just
// return the batch and signal shutdown
if !chanOpen {
return true, batch
}
// Set a timeout if we don't have one
if timeout.C == nil {
defer func(t time.Time) { b.fillTime.UpdateSince(t) }(time.Now())
timeout = time.NewTimer(b.timeout)
defer timeout.Stop() // ensure timer is stopped when done
}
if full := batch.Add(line); full {
return false, batch
}
}
}
}
示例5: 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()
}
示例6: 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)
}
示例7: timedDecoder
// timedDecoder returns a Decorated decoder that generates the given error if no events
// are decoded for some number of sequential timeouts. The returned Decoder is not safe
// to share across goroutines.
// TODO(jdef) this probably isn't the right place for all of this logic (and it's not
// just monitoring the heartbeat messages, it's counting all of them..). Heartbeat monitoring
// has specific requirements. Get rid of this and implement something better elsewhere.
func timedDecoder(dec records.Decoder, dur time.Duration, timeouts int, err error) records.Decoder {
var t *time.Timer
return records.DecoderFunc(func(v interface{}) error {
if t == nil {
t = time.NewTimer(dur)
} else {
t.Reset(dur)
}
defer t.Stop()
errCh := make(chan error, 1)
go func() {
// there's no way to abort this so someone else will have
// to make sure that it dies (and it should if the response
// body is closed)
errCh <- dec.Decode(v)
}()
for x := 0; x < timeouts; x++ {
select {
case <-t.C:
// check for a tie
select {
case e := <-errCh:
return e
default:
// noop, continue
}
case e := <-errCh:
return e
}
}
return err
})
}
示例8: 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.
// returns the channel status, completed batch
func (batcher Batcher) fillBatch() (bool, Batch) {
batch := NewBatch(batcher.batchSize) // Make a batch
timeout := new(time.Timer) // Gives us a nil channel and no timeout to start with
chanOpen := true // Assume the channel is open
count := 0
for {
select {
case <-timeout.C:
return !chanOpen, batch
case line, chanOpen := <-batcher.inLogs:
if !chanOpen {
return !chanOpen, batch
}
// 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.Add(line)
count += 1
if count >= batcher.batchSize {
return !chanOpen, batch
}
}
}
}
示例9: 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
}
示例10: blockingRPC
// blockingRPC is used for queries that need to wait for a
// minimum index. This is used to block and wait for changes.
func (s *Server) blockingRPC(opts *blockingOptions) error {
var timeout *time.Timer
var notifyCh chan struct{}
var state *state.StateStore
// Fast path non-blocking
if opts.queryOpts.MinQueryIndex == 0 {
goto RUN_QUERY
}
// Restrict the max query time, and ensure there is always one
if opts.queryOpts.MaxQueryTime > maxQueryTime {
opts.queryOpts.MaxQueryTime = maxQueryTime
} else if opts.queryOpts.MaxQueryTime <= 0 {
opts.queryOpts.MaxQueryTime = defaultQueryTime
}
// Apply a small amount of jitter to the request
opts.queryOpts.MaxQueryTime += randomStagger(opts.queryOpts.MaxQueryTime / jitterFraction)
// Setup a query timeout
timeout = time.NewTimer(opts.queryOpts.MaxQueryTime)
// Setup the notify channel
notifyCh = make(chan struct{}, 1)
// Ensure we tear down any watchers on return
state = s.fsm.State()
defer func() {
timeout.Stop()
if opts.allocWatch != "" {
state.StopWatchAllocs(opts.allocWatch, notifyCh)
}
}()
REGISTER_NOTIFY:
// Register the notification channel. This may be done
// multiple times if we have not reached the target wait index.
if opts.allocWatch != "" {
state.WatchAllocs(opts.allocWatch, notifyCh)
}
RUN_QUERY:
// Update the query meta data
s.setQueryMeta(opts.queryMeta)
// Run the query function
metrics.IncrCounter([]string{"nomad", "rpc", "query"}, 1)
err := opts.run()
// Check for minimum query time
if err == nil && opts.queryMeta.Index > 0 && opts.queryMeta.Index <= opts.queryOpts.MinQueryIndex {
select {
case <-notifyCh:
goto REGISTER_NOTIFY
case <-timeout.C:
}
}
return err
}
示例11: releaseTimer
func releaseTimer(t *time.Timer, wasRead bool) {
stopped := t.Stop()
if !wasRead && !stopped {
<-t.C
}
timerPool.Put(t)
}
示例12: 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
}
}
}
示例13: 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
}
}
}
}
示例14: GetDuplicates
// GetDuplicates returns all the duplicate evaluations and blocks until the
// passed timeout.
func (b *BlockedEvals) GetDuplicates(timeout time.Duration) []*structs.Evaluation {
var timeoutTimer *time.Timer
var timeoutCh <-chan time.Time
SCAN:
b.l.Lock()
if len(b.duplicates) != 0 {
dups := b.duplicates
b.duplicates = nil
b.l.Unlock()
return dups
}
b.l.Unlock()
// Create the timer
if timeoutTimer == nil && timeout != 0 {
timeoutTimer = time.NewTimer(timeout)
timeoutCh = timeoutTimer.C
defer timeoutTimer.Stop()
}
select {
case <-b.stopCh:
return nil
case <-timeoutCh:
return nil
case <-b.duplicateCh:
goto SCAN
}
}
示例15: 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
}