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


Golang Time.UnixNano方法代码示例

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


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

示例1: shouldRunContinuousQuery

// shouldRunContinuousQuery returns true if the CQ should be schedule to run. It will use the
// lastRunTime of the CQ and the rules for when to run set through the query to determine
// if this CQ should be run
func (cq *ContinuousQuery) shouldRunContinuousQuery(now time.Time) (bool, time.Time, error) {
	// if it's not aggregated we don't run it
	if cq.q.IsRawQuery {
		return false, cq.LastRun, errors.New("continuous queries must be aggregate queries")
	}

	// since it's aggregated we need to figure how often it should be run
	interval, err := cq.q.GroupByInterval()
	if err != nil {
		return false, cq.LastRun, err
	}

	// allow the interval to be overwritten by the query's resample options
	resampleEvery := interval
	if cq.Resample.Every != 0 {
		resampleEvery = cq.Resample.Every
	}

	// if we've passed the amount of time since the last run, or there was no last run, do it up
	if cq.HasRun {
		nextRun := cq.LastRun.Add(resampleEvery)
		if nextRun.UnixNano() <= now.UnixNano() {
			return true, nextRun, nil
		}
	} else {
		return true, now, nil
	}

	return false, cq.LastRun, nil
}
开发者ID:jsternberg,项目名称:influxdb,代码行数:33,代码来源:service.go

示例2: setClock

func setClock(t time.Time) error {
	tv := syscall.NsecToTimeval(t.UnixNano())
	if err := syscall.Settimeofday(&tv); err != nil {
		return errors.New("settimeofday: " + err.Error())
	}
	return nil
}
开发者ID:ality,项目名称:go-tlsdate,代码行数:7,代码来源:time_posix.go

示例3: setTime

func (d *deadline) setTime(t time.Time) {
	if t.IsZero() {
		d.set(0)
	} else {
		d.set(t.UnixNano())
	}
}
开发者ID:ZeusbasePython,项目名称:appscale,代码行数:7,代码来源:net.go

示例4: Route

// Route routes an update packet to the correct server.
func (r *Router) Route(cancelSignal <-chan bool, uaid, chid string, version int64, sentAt time.Time, logID string) (err error) {
	startTime := time.Now()
	locator := r.Locator()
	if locator == nil {
		if r.logger.ShouldLog(ERROR) {
			r.logger.Error("router", "No discovery service set; unable to route message",
				LogFields{"rid": logID, "uaid": uaid, "chid": chid})
		}
		r.metrics.Increment("router.broadcast.error")
		return ErrNoLocator
	}
	segment := capn.NewBuffer(nil)
	routable := NewRootRoutable(segment)
	routable.SetChannelID(chid)
	routable.SetVersion(version)
	routable.SetTime(sentAt.UnixNano())
	contacts, err := locator.Contacts(uaid)
	if err != nil {
		if r.logger.ShouldLog(CRITICAL) {
			r.logger.Critical("router", "Could not query discovery service for contacts",
				LogFields{"rid": logID, "error": err.Error()})
		}
		r.metrics.Increment("router.broadcast.error")
		return err
	}
	if r.logger.ShouldLog(DEBUG) {
		r.logger.Debug("router", "Fetched contact list from discovery service",
			LogFields{"rid": logID, "servers": strings.Join(contacts, ", ")})
	}
	if r.logger.ShouldLog(INFO) {
		r.logger.Info("router", "Sending push...", LogFields{
			"rid":     logID,
			"uaid":    uaid,
			"chid":    chid,
			"version": strconv.FormatInt(version, 10),
			"time":    strconv.FormatInt(sentAt.UnixNano(), 10)})
	}
	ok, err := r.notifyAll(cancelSignal, contacts, uaid, segment, logID)
	endTime := time.Now()
	if err != nil {
		if r.logger.ShouldLog(WARNING) {
			r.logger.Warn("router", "Could not post to server",
				LogFields{"rid": logID, "error": err.Error()})
		}
		r.metrics.Increment("router.broadcast.error")
		return err
	}
	var counterName, timerName string
	if ok {
		counterName = "router.broadcast.hit"
		timerName = "updates.routed.hits"
	} else {
		counterName = "router.broadcast.miss"
		timerName = "updates.routed.misses"
	}
	r.metrics.Increment(counterName)
	r.metrics.Timer(timerName, endTime.Sub(sentAt))
	r.metrics.Timer("router.handled", endTime.Sub(startTime))
	return nil
}
开发者ID:shihuacai1989,项目名称:pushgo,代码行数:61,代码来源:router.go

示例5: report

func (sl *scrapeLoop) report(start time.Time, duration time.Duration, err error) {
	sl.scraper.report(start, duration, err)

	ts := model.TimeFromUnixNano(start.UnixNano())

	var health model.SampleValue
	if err == nil {
		health = 1
	}

	healthSample := &model.Sample{
		Metric: model.Metric{
			model.MetricNameLabel: scrapeHealthMetricName,
		},
		Timestamp: ts,
		Value:     health,
	}
	durationSample := &model.Sample{
		Metric: model.Metric{
			model.MetricNameLabel: scrapeDurationMetricName,
		},
		Timestamp: ts,
		Value:     model.SampleValue(float64(duration) / float64(time.Second)),
	}

	sl.reportAppender.Append(healthSample)
	sl.reportAppender.Append(durationSample)
}
开发者ID:yershalom,项目名称:prometheus,代码行数:28,代码来源:scrape.go

示例6: advance

// advance cycles the buckets at each level until the latest bucket in
// each level can hold the time specified.
func (ts *timeSeries) advance(t time.Time) {
	if !t.After(ts.levels[0].end) {
		return
	}
	for i := 0; i < len(ts.levels); i++ {
		level := ts.levels[i]
		if !level.end.Before(t) {
			break
		}

		// If the time is sufficiently far, just clear the level and advance
		// directly.
		if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) {
			for _, b := range level.buckets {
				ts.resetObservation(b)
			}
			level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds())
		}

		for t.After(level.end) {
			level.end = level.end.Add(level.size)
			level.newest = level.oldest
			level.oldest = (level.oldest + 1) % ts.numBuckets
			ts.resetObservation(level.buckets[level.newest])
		}

		t = level.end
	}
}
开发者ID:2722,项目名称:lantern,代码行数:31,代码来源:timeseries.go

示例7: Backup

// Backup will write a tar archive of any TSM files modified since the passed
// in time to the passed in writer. The basePath will be prepended to the names
// of the files in the archive. It will force a snapshot of the WAL first
// then perform the backup with a read lock against the file store. This means
// that new TSM files will not be able to be created in this shard while the
// backup is running. For shards that are still acively getting writes, this
// could cause the WAL to backup, increasing memory usage and evenutally rejecting writes.
func (e *Engine) Backup(w io.Writer, basePath string, since time.Time) error {
	if err := e.WriteSnapshot(); err != nil {
		return err
	}
	e.FileStore.mu.RLock()
	defer e.FileStore.mu.RUnlock()

	var files []FileStat

	// grab all the files and tombstones that have a modified time after since
	for _, f := range e.FileStore.files {
		if stat := f.Stats(); stat.LastModified > since.UnixNano() {
			files = append(files, f.Stats())
		}
		for _, t := range f.TombstoneFiles() {
			if t.LastModified > since.UnixNano() {
				files = append(files, f.Stats())
			}
		}
	}

	tw := tar.NewWriter(w)
	defer tw.Close()

	for _, f := range files {
		if err := e.writeFileToBackup(f, basePath, tw); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:jipperinbham,项目名称:influxdb,代码行数:39,代码来源:engine.go

示例8: WriteBulkBytes

// Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index
// http://www.elasticsearch.org/guide/reference/api/bulk.html
func WriteBulkBytes(op string, index string, _type string, id, parent, ttl string, date *time.Time, data interface{}) ([]byte, error) {
	// only index and update are currently supported
	if op != "index" && op != "update" && op != "create" {
		return nil, errors.New(fmt.Sprintf("Operation '%s' is not yet supported", op))
	}

	// First line
	buf := bytes.Buffer{}
	buf.WriteString(fmt.Sprintf(`{"%s":{"_index":"`, op))
	buf.WriteString(index)
	buf.WriteString(`","_type":"`)
	buf.WriteString(_type)
	buf.WriteString(`"`)
	if len(id) > 0 {
		buf.WriteString(`,"_id":"`)
		buf.WriteString(id)
		buf.WriteString(`"`)
	}

	if len(parent) > 0 {
		buf.WriteString(`,"_parent":"`)
		buf.WriteString(parent)
		buf.WriteString(`"`)
	}

	if op == "update" {
		buf.WriteString(`,"_retry_on_conflict":3`)
	}

	if len(ttl) > 0 {
		buf.WriteString(`,"ttl":"`)
		buf.WriteString(ttl)
		buf.WriteString(`"`)
	}
	if date != nil {
		buf.WriteString(`,"_timestamp":"`)
		buf.WriteString(strconv.FormatInt(date.UnixNano()/1e6, 10))
		buf.WriteString(`"`)
	}

	buf.WriteString(`}}`)
	buf.WriteRune('\n')
	//buf.WriteByte('\n')
	switch v := data.(type) {
	case *bytes.Buffer:
		io.Copy(&buf, v)
	case []byte:
		buf.Write(v)
	case string:
		buf.WriteString(v)
	default:
		body, jsonErr := json.Marshal(data)
		if jsonErr != nil {
			return nil, jsonErr
		}
		buf.Write(body)
	}
	buf.WriteRune('\n')
	return buf.Bytes(), nil
}
开发者ID:steeve,项目名称:elastigo,代码行数:62,代码来源:corebulk.go

示例9: report

func (sl *scrapeLoop) report(start time.Time, duration time.Duration, err error) {
	sl.scraper.report(start, duration, err)

	ts := model.TimeFromUnixNano(start.UnixNano())

	var health model.SampleValue
	if err == nil {
		health = 1
	}

	healthSample := &model.Sample{
		Metric: model.Metric{
			model.MetricNameLabel: scrapeHealthMetricName,
		},
		Timestamp: ts,
		Value:     health,
	}
	durationSample := &model.Sample{
		Metric: model.Metric{
			model.MetricNameLabel: scrapeDurationMetricName,
		},
		Timestamp: ts,
		Value:     model.SampleValue(float64(duration) / float64(time.Second)),
	}

	if err := sl.reportAppender.Append(healthSample); err != nil {
		log.With("sample", healthSample).With("error", err).Warn("Scrape health sample discarded")
	}
	if err := sl.reportAppender.Append(durationSample); err != nil {
		log.With("sample", durationSample).With("error", err).Warn("Scrape duration sample discarded")
	}
}
开发者ID:RichiH,项目名称:prometheus,代码行数:32,代码来源:scrape.go

示例10: Touch

func (ss *SimpleRate) Touch(key string, nowTs time.Time) {
	var (
		found  bool
		bucket *srateBucket
		now    = nowTs.UnixNano()
	)
	bucket, found = ss.hash[key]
	if found {
		// we already have the correct bucket
	} else if len(ss.heap) < ss.size {
		// create new bucket
		bucket = &srateBucket{}
		ss.hash[key] = bucket
		bucket.key = key
		heap.Push(&ss.heap, bucket)
	} else {
		// use minimum bucket
		bucket = ss.heap[0]
		delete(ss.hash, bucket.key)
		ss.hash[key] = bucket
		bucket.error, bucket.errorTs, bucket.errorRate =
			bucket.count, bucket.countTs, bucket.countRate
		bucket.key = key
	}

	bucket.count += 1
	bucket.countRate = ss.count(bucket.countRate, bucket.countTs, now)
	bucket.countTs = now

	heap.Fix(&ss.heap, bucket.index)
}
开发者ID:wheelcomplex,项目名称:golibs,代码行数:31,代码来源:srate.go

示例11: passDetails

func passDetails(
	binary_path string,
	begin_time time.Time,
	duration time.Duration,
	latitude_degrees,
	longitude_degrees,
	elevation_metres float64,
	tle string,
	resolution_seconds float64) ([]SatPoint, error) {

	begin_timestamp := 1e-9 * float64(begin_time.UnixNano())

	c := exec.Command("python", binary_path)
	in_pipe, err := c.StdinPipe()
	if err != nil {
		return nil, err
	}
	defer in_pipe.Close()
	out_pipe, err := c.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer out_pipe.Close()
	if err := c.Start(); err != nil {
		return nil, err
	}
	defer c.Wait()

	fmt.Fprintf(in_pipe, "%f\n%f\n%f\n%f\n%f\n%s\n%f\n",
		begin_timestamp,
		duration.Seconds(),
		latitude_degrees,
		longitude_degrees,
		elevation_metres,
		tle,
		resolution_seconds)
	in_pipe.Close()

	var n int
	_, err = fmt.Fscanln(out_pipe, &n)
	if err != nil {
		return nil, err
	}

	r := make([]SatPoint, n)
	for i := 0; i < n; i++ {
		p := &r[i]
		fmt.Fscanln(out_pipe,
			&p.Timestamp,
			&p.AzimuthDegrees,
			&p.AltitudeDegrees,
			&p.Range,
			&p.RangeVelocity,
			&p.LatitudeDegrees,
			&p.LongitudeDegrees,
			&p.Elevation,
			&p.IsEclipsed)
	}
	return r, nil
}
开发者ID:tstranex,项目名称:carpcomm,代码行数:60,代码来源:pass_details.go

示例12: makeLoginResponse

func (h *MatrixLoginHandler) makeLoginResponse(userID string, expires time.Time, nonce string) (*matrixLoginResponse, error) {

	var response matrixLoginResponse

	accessToken, err := macaroon.New([]byte(h.macaroonSecret), "key", h.serverName)
	if err != nil {
		return nil, err
	}
	accessToken.AddFirstPartyCaveat("gen = 1")
	accessToken.AddFirstPartyCaveat(fmt.Sprintf("user_id = %s", userID))
	refreshToken := accessToken.Clone()

	accessToken.AddFirstPartyCaveat("type = access")
	accessToken.AddFirstPartyCaveat(fmt.Sprintf("time < %d", expires.UnixNano()/1000000))

	refreshToken.AddFirstPartyCaveat("type = refresh")
	refreshToken.AddFirstPartyCaveat(fmt.Sprintf("nonce = %s", nonce))

	if response.AccessToken, err = encodeMacaroon(accessToken); err != nil {
		return nil, err
	}

	if response.RefreshToken, err = encodeMacaroon(refreshToken); err != nil {
		return nil, err
	}

	response.HomeServer = h.serverName
	response.UserID = userID

	return &response, nil
}
开发者ID:NegativeMjark,项目名称:dendron,代码行数:31,代码来源:login.go

示例13: TimeToTimestamp

// TimeToTimestamp is a utility function that converts a time.Time into
// a *google_protobuf.Timestamp.
func TimeToTimestamp(t time.Time) *google_protobuf.Timestamp {
	unixNano := t.UnixNano()
	return &google_protobuf.Timestamp{
		Seconds: unixNano / int64(time.Second),
		Nanos:   int32(unixNano % int64(time.Second)),
	}
}
开发者ID:kunthar,项目名称:pachyderm,代码行数:9,代码来源:protolog.go

示例14: stamp

func (d *Datum) stamp(timestamp time.Time) {
	if timestamp.IsZero() {
		atomic.StoreInt64(&d.Time, time.Now().UTC().UnixNano())
	} else {
		atomic.StoreInt64(&d.Time, timestamp.UnixNano())
	}
}
开发者ID:yanghongkjxy,项目名称:mtail,代码行数:7,代码来源:datum.go

示例15: pnTime

// pnTime converts Go time.Time to Proton millisecond Unix time.
func pnTime(t time.Time) C.pn_timestamp_t {
	secs := t.Unix()
	// Note: sub-second accuracy is not guaraunteed if the Unix time in
	// nanoseconds cannot be represented by an int64 (sometime around year 2260)
	msecs := (t.UnixNano() % int64(time.Second)) / int64(time.Millisecond)
	return C.pn_timestamp_t(secs*1000 + msecs)
}
开发者ID:Karm,项目名称:qpid-proton,代码行数:8,代码来源:types.go


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