本文整理汇总了Golang中Time.Time.IsZero方法的典型用法代码示例。如果您正苦于以下问题:Golang Time.IsZero方法的具体用法?Golang Time.IsZero怎么用?Golang Time.IsZero使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Time
的用法示例。
在下文中一共展示了Time.IsZero方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Add
// Add adds new node and returns it, it replaces existing without notification.
func (s *nodeStore) Add(n *api.Node, expireFunc func()) *registeredNode {
s.mu.Lock()
defer s.mu.Unlock()
var attempts int
var registered time.Time
if existRn, ok := s.nodes[n.ID]; ok {
attempts = existRn.Attempts
registered = existRn.Registered
existRn.Heartbeat.Stop()
delete(s.nodes, n.ID)
}
if registered.IsZero() {
registered = time.Now()
}
rn := ®isteredNode{
SessionID: identity.NewID(), // session ID is local to the dispatcher.
Node: n,
Registered: registered,
Attempts: attempts,
Disconnect: make(chan struct{}),
}
s.nodes[n.ID] = rn
rn.Heartbeat = heartbeat.New(s.periodChooser.Choose()*s.gracePeriodMultiplierNormal, expireFunc)
return rn
}
示例2: next
func (df *datanodeFailover) next() string {
if df.numRemaining() == 0 {
return ""
}
var picked = -1
var oldestFailure time.Time
for i, address := range df.datanodes {
datanodeFailuresLock.Lock()
failedAt, hasFailed := datanodeFailures[address]
datanodeFailuresLock.Unlock()
if !hasFailed {
picked = i
break
} else if oldestFailure.IsZero() || failedAt.Before(oldestFailure) {
picked = i
oldestFailure = failedAt
}
}
address := df.datanodes[picked]
df.datanodes = append(df.datanodes[:picked], df.datanodes[picked+1:]...)
df.currentDatanode = address
return address
}
示例3: Enqueue
// Enqueue is a convenience function to push a message to a channel while
// waiting for a timeout instead of just blocking.
// Passing a timeout of -1 will discard the message.
// Passing a timout of 0 will always block.
// Messages that time out will be passed to the dropped queue if a Dropped
// consumer exists.
// The source parameter is used when a message is dropped, i.e. it is passed
// to the Drop function.
func (msg Message) Enqueue(channel chan<- Message, timeout time.Duration) MessageState {
if timeout == 0 {
channel <- msg
return MessageStateOk // ### return, done ###
}
start := time.Time{}
spin := shared.Spinner{}
for {
select {
case channel <- msg:
return MessageStateOk // ### return, done ###
default:
switch {
// Start timeout based retries
case start.IsZero():
if timeout < 0 {
return MessageStateDiscard // ### return, discard and ignore ###
}
start = time.Now()
spin = shared.NewSpinner(shared.SpinPriorityHigh)
// Discard message after timeout
case time.Since(start) > timeout:
return MessageStateTimeout // ### return, drop and retry ###
// Yield and try again
default:
spin.Yield()
}
}
}
}
示例4: showSince
func showSince(writer io.Writer, now time.Time, since time.Time) {
if now.IsZero() || since.IsZero() {
fmt.Fprintln(writer, " <td></td>")
} else {
showDuration(writer, now.Sub(since), false)
}
}
示例5: humanizeTime
func humanizeTime(t time.Time) string {
if t.IsZero() {
return ""
} else {
return humanize.Time(t)
}
}
示例6: generateDerCert
func generateDerCert(privKey *rsa.PrivateKey, expiration time.Time, domain string) ([]byte, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
if expiration.IsZero() {
expiration = time.Now().Add(365)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: "ACME Challenge TEMP",
},
NotBefore: time.Now(),
NotAfter: expiration,
KeyUsage: x509.KeyUsageKeyEncipherment,
BasicConstraintsValid: true,
DNSNames: []string{domain},
}
return x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
}
示例7: retrieveChangeSets
func (p *InMemoryDataStore) retrieveChangeSets(dsocialId string, after time.Time) ([]*dm.ChangeSet, bc.NextToken, error) {
l := list.New()
var afterString string
if !after.IsZero() {
afterString = after.Format(dm.UTC_DATETIME_FORMAT)
}
for _, v := range p.retrieveChangesetCollection().Data {
if cs, ok := v.(*dm.ChangeSet); ok {
if cs.RecordId == dsocialId {
if after.IsZero() || cs.CreatedAt > afterString {
cs2 := new(dm.ChangeSet)
*cs2 = *cs
l.PushBack(cs2)
}
}
}
}
rc := make([]*dm.ChangeSet, l.Len())
for i, iter := 0, l.Front(); iter != nil; i, iter = i+1, iter.Next() {
if iter.Value != nil {
rc[i] = iter.Value.(*dm.ChangeSet)
}
}
return rc, nil, nil
}
示例8: dialChannel
// dialChannel is the simple pure-Go implementation of dial, still
// used on operating systems where the deadline hasn't been pushed
// down into the pollserver. (Plan 9 and some old versions of Windows)
func dialChannel(net string, ra Addr, dialer func(time.Time) (Conn, error), deadline time.Time) (Conn, error) {
var timeout time.Duration
if !deadline.IsZero() {
timeout = deadline.Sub(time.Now())
}
if timeout <= 0 {
return dialer(noDeadline)
}
t := time.NewTimer(timeout)
defer t.Stop()
type racer struct {
Conn
error
}
ch := make(chan racer, 1)
go func() {
if testingIssue5349 {
time.Sleep(time.Millisecond)
}
c, err := dialer(noDeadline)
ch <- racer{c, err}
}()
select {
case <-t.C:
return nil, &OpError{Op: "dial", Net: net, Addr: ra, Err: errTimeout}
case racer := <-ch:
return racer.Conn, racer.error
}
}
示例9: timeAsString
func timeAsString(gotime time.Time, unit units.Unit) string {
var dur duration.Duration
if !gotime.IsZero() {
dur = duration.SinceEpoch(gotime)
}
return dur.StringUsingUnits(unit)
}
示例10: SetExpires
// SetExpires - Sets expiration time for the new policy.
func (p *PostPolicy) SetExpires(t time.Time) error {
if t.IsZero() {
return ErrInvalidArgument("No expiry time set.")
}
p.expiration = t
return nil
}
示例11: tailFile
func tailFile(f io.ReadSeeker, logWatcher *logger.LogWatcher, tail int, since time.Time) {
var rdr io.Reader = f
if tail > 0 {
ls, err := tailfile.TailFile(f, tail)
if err != nil {
logWatcher.Err <- err
return
}
rdr = bytes.NewBuffer(bytes.Join(ls, []byte("\n")))
}
dec := json.NewDecoder(rdr)
l := &jsonlog.JSONLog{}
for {
msg, err := decodeLogLine(dec, l)
if err != nil {
if err != io.EOF {
logWatcher.Err <- err
}
return
}
if !since.IsZero() && msg.Timestamp.Before(since) {
continue
}
logWatcher.Msg <- msg
}
}
示例12: lookupIPDeadline
// lookupIPDeadline looks up a hostname with a deadline.
func lookupIPDeadline(host string, deadline time.Time) (addrs []IPAddr, err error) {
if deadline.IsZero() {
return lookupIPMerge(host)
}
// We could push the deadline down into the name resolution
// functions. However, the most commonly used implementation
// calls getaddrinfo, which has no timeout.
timeout := deadline.Sub(time.Now())
if timeout <= 0 {
return nil, errTimeout
}
t := time.NewTimer(timeout)
defer t.Stop()
ch := lookupGroup.DoChan(host, func() (interface{}, error) {
return testHookLookupIP(lookupIP, host)
})
select {
case <-t.C:
// The DNS lookup timed out for some reason. Force
// future requests to start the DNS lookup again
// rather than waiting for the current lookup to
// complete. See issue 8602.
lookupGroup.Forget(host)
return nil, errTimeout
case r := <-ch:
return lookupIPReturn(r.Val, r.Err, r.Shared)
}
}
示例13: UnmarshalJSON
func (t *Time) UnmarshalJSON(data []byte) error {
var err error
var parsedTime time.Time
if string(data) == "null" {
*t = Time(time.Time{})
return nil
}
layouts := []string{
"2006-01-02 15:04:05 UTC",
"2006-01-02 15:04:05+00",
"2006-01-02T15:04:05.999999Z",
"2006-01-02 15:04:05.999999",
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05.999999+00"}
for _, layout := range layouts {
parsedTime, err = time.Parse(layout,
strings.Replace(string(data), "\"", "", -1))
if err != nil {
continue
}
break
}
if parsedTime.IsZero() {
return err
}
*t = Time(parsedTime)
return nil
}
示例14: addToCache
// Make sure to call with the mutex locked
func (db *BlockDB) addToCache(h *btc.Uint256, bl []byte, str *btc.Block) (crec *BlckCachRec) {
if db.cache == nil {
return
}
crec = db.cache[h.BIdx()]
if crec != nil {
crec.Data = bl
if str != nil {
crec.Block = str
}
crec.LastUsed = time.Now()
return
}
if len(db.cache) >= db.max_cached_blocks {
var oldest_t time.Time
var oldest_k [btc.Uint256IdxLen]byte
for k, v := range db.cache {
if oldest_t.IsZero() || v.LastUsed.Before(oldest_t) {
oldest_t = v.LastUsed
oldest_k = k
}
}
delete(db.cache, oldest_k)
}
crec = &BlckCachRec{LastUsed: time.Now(), Data: bl, Block: str}
db.cache[h.BIdx()] = crec
return
}
示例15: TimeToAnneesMoisJour
// Crée un nouvel objet de type AnneesMoisJours pour la date spécifiée
func TimeToAnneesMoisJour(t time.Time) (AnneesMoisJours, error) {
if t.IsZero() {
return AnneesMoisJours{}, ErrDateFormatInvalide
}
return AnneesMoisJours{t.Year(), int(t.Month()), t.Day()}, nil
}