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


Golang Time.Now函数代码示例

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


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

示例1: GetToken

// GetToken wraps the incoming username into a TokenStruct, serializes the result to json
// and generates a Fernet token based on the resulting string
func GetToken(username string) string {
	// If the configuration has changed, re-load the keys
	if confVersion != util.GetConfig().Version {
		loadMintKey()
	}

	claims := jwt.StandardClaims{
		Issuer:    "FoxAuthn",
		Subject:   username,
		IssuedAt:  time.Now().Unix(),
		ExpiresAt: time.Now().Add(time.Duration(util.GetConfig().Authn.TokenTTL) * time.Second).Unix(),
	}

	log.WithFields(log.Fields{
		"claims": claims,
	}).Debug("Going to sign with these claims")

	token := jwt.NewWithClaims(jwt.SigningMethodRS384, claims)
	ss, err := token.SignedString(GetKey())
	if err != nil {
		log.WithFields(log.Fields{
			"path": mint.From,
		}).Panic("Failed to create signed token: ", err)
	}
	return ss
}
开发者ID:e-gov,项目名称:fox,代码行数:28,代码来源:Mint.go

示例2: sshClientActivity

func sshClientActivity(index int) {
	sc := sshConns[index]

	s := rand.NewSource(time.Now().UnixNano())
	r := rand.New(s)

	// generate a random byte slice
	l := r.Intn(128)
	b := make([]byte, l)
	for i, _ := range b {
		b[i] = byte(r.Int())
	}

	data := base64.StdEncoding.EncodeToString(b)
	log.Debug("ssh activity to %v with %v", sc.Host, data)

	start := time.Now().UnixNano()

	sc.Stdin.Write([]byte(data))
	sc.Stdin.Write([]byte{'\r', '\n'})
	sshReportChan <- uint64(len(data))

	expected := fmt.Sprintf("> %v\r\n%v\r\n> ", data, data)
	for i := 0; i < 10 && sc.StdoutBuf.String() != expected; i++ {
		time.Sleep(100 * time.Millisecond)
	}

	stop := time.Now().UnixNano()
	log.Info("ssh %v %vns", sc.Host, uint64(stop-start))

	log.Debugln("ssh: ", sc.StdoutBuf.String())

	sc.StdoutBuf.Reset()
}
开发者ID:cdshann,项目名称:minimega,代码行数:34,代码来源:ssh.go

示例3: newRepo

func newRepo(name string, simpleDocker SimpleDocker.SimpleDocker) (Repo, error) {
	log.WithFields(log.Fields{
		"name": name,
	}).Info("Creating new repo")

	r := Repo{
		Name:         name,
		SimpleDocker: simpleDocker,
	}

	startTime := time.Now()
	repoName := fmt.Sprintf("ihsw/%s", name)
	if err := r.pullImage(repoName); err != nil {
		log.WithFields(log.Fields{
			"name":     name,
			"err":      err.Error(),
			"repoName": repoName,
		}).Warn("Could not pull image")

		return Repo{}, err
	}

	log.WithFields(log.Fields{
		"name":     name,
		"duration": fmt.Sprintf("%v", time.Now().Sub(startTime)),
	}).Info("Repo create success")

	return r, nil
}
开发者ID:galactic-filament,项目名称:the-matrix,代码行数:29,代码来源:Repo.go

示例4: work

func work(c *replicant.Client, C <-chan time.Time, stop chan bool, done chan bool, dl *ygor.DataLogger) {
	defer func() {
		done <- true
	}()
	for {
		select {
		case <-C:
			break
		case <-stop:
			return
		}
		start := time.Now()
		_, err := c.Call("echo", "echo", []byte("hello world"), 0)
		end := time.Now()
		if err.Status == replicant.SUCCESS {
			when := uint64(end.UnixNano())
			data := uint64(end.Sub(start).Nanoseconds())
			er := dl.Record(1, when, data)
			if er != nil {
				fmt.Printf("error: %s\n", er)
				os.Exit(1)
			}
		} else {
			fmt.Printf("error: %s\n", err)
			os.Exit(1)
		}
	}
}
开发者ID:rescrv,项目名称:Replicant,代码行数:28,代码来源:main.go

示例5: PutMessage

// receive from leader
func (self *NsqdCoordRpcServer) PutMessage(info *RpcPutMessage) *CoordErr {
	if self.nsqdCoord.enableBenchCost || coordLog.Level() >= levellogger.LOG_DEBUG {
		s := time.Now()
		defer func() {
			e := time.Now()
			if e.Sub(s) > time.Second*time.Duration(RPC_TIMEOUT/2) {
				coordLog.Infof("PutMessage rpc call used: %v, start: %v, end: %v", e.Sub(s), s, e)
			}
			coordLog.Warningf("PutMessage rpc call used: %v, start: %v, end: %v", e.Sub(s), s, e)
		}()
	}

	var ret CoordErr
	defer coordErrStats.incCoordErr(&ret)
	tc, err := self.nsqdCoord.checkWriteForRpcCall(info.RpcTopicData)
	if err != nil {
		ret = *err
		return &ret
	}
	// do local pub message
	err = self.nsqdCoord.putMessageOnSlave(tc, info.LogData, info.TopicMessage)
	if err != nil {
		ret = *err
		return &ret
	}
	return &ret
}
开发者ID:absolute8511,项目名称:nsq,代码行数:28,代码来源:coordinator_rpc.go

示例6: DefaultHandler

func DefaultHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Serving index.html to ", r.RemoteAddr)

	tmpl, err := template.ParseFiles("templates/index.html")
	if err != nil {
		Write404(w, r)
		log.Println("error loading index.html!")
		return
	}

	if client, ok := clientList[r.RemoteAddr]; ok {
		client.LastUpdate = time.Now()
		clientList[r.RemoteAddr] = client
	} else {
		mutex.Lock()
		client := clientInfo{
			NodeID:     "SC-0.1-" + strconv.Itoa(GNodeID),
			Address:    net.ParseIP(r.RemoteAddr),
			LastUpdate: time.Now(),
		}
		GNodeID++
		mutex.Unlock()

		clientList[r.RemoteAddr] = client
	}

	tmpl.Execute(w, struct {
		NodeID   string
		NumNodes int
	}{clientList[r.RemoteAddr].NodeID, len(clientList)})
}
开发者ID:gearmover,项目名称:myownsupercomputer,代码行数:31,代码来源:main.go

示例7: RunServerWithAuth

// New Go Routine based server with auth
func RunServerWithAuth(opts *server.Options, auth server.Auth) *server.Server {
	if opts == nil {
		opts = &DefaultTestOptions
	}
	s := server.New(opts)
	if s == nil {
		panic("No NATS Server object returned.")
	}

	if auth != nil {
		s.SetAuthMethod(auth)
	}

	// Run server in Go routine.
	go s.Start()

	end := time.Now().Add(10 * time.Second)
	for time.Now().Before(end) {
		addr := s.Addr()
		if addr == nil {
			time.Sleep(50 * time.Millisecond)
			// Retry. We might take a little while to open a connection.
			continue
		}
		conn, err := net.Dial("tcp", addr.String())
		if err != nil {
			// Retry after 50ms
			time.Sleep(50 * time.Millisecond)
			continue
		}
		conn.Close()
		return s
	}
	panic("Unable to start NATS Server in Go Routine")
}
开发者ID:Workiva,项目名称:thrift-nats,代码行数:36,代码来源:test.go

示例8: Loop

func (b *Broker) Loop(decorate bool) {
	b.start = time.Now()

	if decorate {
		go b.SendNoLog(Response{
			Token: "margo.hello",
			Data: M{
				"time": b.start.String(),
			},
		})
	}

	for {
		stopLooping := b.accept()
		if stopLooping {
			break
		}
		runtime.Gosched()
	}

	if decorate {
		b.SendNoLog(Response{
			Token: "margo.bye-ni",
			Data: M{
				"served": b.served,
				"uptime": time.Now().Sub(b.start).String(),
			},
		})
	}
}
开发者ID:ntcong,项目名称:sublime-text-2-config,代码行数:30,代码来源:broker.go

示例9: controlService

func controlService(name string, c svc.Cmd, to svc.State) error {
	m, err := mgr.Connect()
	if err != nil {
		return err
	}
	defer m.Disconnect()
	s, err := m.OpenService(name)
	if err != nil {
		return fmt.Errorf("could not access service: %v", err)
	}
	defer s.Close()
	status, err := s.Control(c)
	if err != nil {
		return fmt.Errorf("could not send control=%d: %v", c, err)
	}
	timeout := time.Now().Add(10 * time.Second)
	for status.State != to {
		if timeout.Before(time.Now()) {
			return fmt.Errorf("timeout waiting for service to go to state=%d", to)
		}
		time.Sleep(300 * time.Millisecond)
		status, err = s.Query()
		if err != nil {
			return fmt.Errorf("could not retrieve service status: %v", err)
		}
	}
	return nil
}
开发者ID:eswdd,项目名称:bosun,代码行数:28,代码来源:service_windows.go

示例10: UpdateActivation

// UpdateActivation updates one build with the given id
// to the given activation setting.
func UpdateActivation(buildId string, active bool, caller string) error {
	var err error
	if !active && (evergreen.IsSystemActivator(caller)) {
		_, err = UpdateAllBuilds(
			bson.M{IdKey: buildId,
				ActivatedByKey: caller,
			},
			bson.M{
				"$set": bson.M{
					ActivatedKey:     active,
					ActivatedTimeKey: time.Now(),
					ActivatedByKey:   caller,
				},
			},
		)
	} else {
		_, err = UpdateAllBuilds(
			bson.M{IdKey: buildId},
			bson.M{
				"$set": bson.M{
					ActivatedKey:     active,
					ActivatedTimeKey: time.Now(),
					ActivatedByKey:   caller,
				},
			},
		)
	}
	return err

}
开发者ID:tychoish,项目名称:evergreen,代码行数:32,代码来源:build.go

示例11: TestChunkerWithRandomPolynomial

func TestChunkerWithRandomPolynomial(t *testing.T) {
	// setup data source
	buf := getRandom(23, 32*1024*1024)

	// generate a new random polynomial
	start := time.Now()
	p, err := RandomPolynomial()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("generating random polynomial took %v", time.Since(start))

	start = time.Now()
	ch := New(bytes.NewReader(buf), p)
	t.Logf("creating chunker took %v", time.Since(start))

	// make sure that first chunk is different
	c, err := ch.Next(nil)
	if err != nil {
		t.Fatal(err.Error())
	}

	if c.Cut == chunks1[0].CutFP {
		t.Fatal("Cut point is the same")
	}

	if c.Length == chunks1[0].Length {
		t.Fatal("Length is the same")
	}

	if bytes.Equal(hashData(c.Data), chunks1[0].Digest) {
		t.Fatal("Digest is the same")
	}
}
开发者ID:ckemper67,项目名称:restic,代码行数:34,代码来源:chunker_test.go

示例12: RoundTrip

func (t *timeoutTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	if time.Now().After(t.Timeout) {
		t.Transport.CloseIdleConnections()
		t.Timeout = time.Now().Add(time.Minute * 5)
	}
	return t.Transport.RoundTrip(r)
}
开发者ID:pdf,项目名称:bosun,代码行数:7,代码来源:collect.go

示例13: SaveState

func (m *MonDB) SaveState(StartIndex int64) error {
	session, err := m.getSession()
	if err != nil {
		log.Print("DB connection error\n")
		return err
	}

	col := session.DB("").C("state")
	var needInsert bool
	state := MonDBState{}
	err = col.Find(nil).Sort("-updated").One(&state)
	if err != nil {
		needInsert = true
	}

	if !needInsert {
		qs := bson.M{"_id": state.Id}
		change := bson.M{"$set": bson.M{"start_index": StartIndex, "updated": time.Now().UTC()}}
		return col.Update(qs, change)
	}

	state.Id = bson.NewObjectId()
	state.StartIndex = StartIndex
	state.Created = time.Now().UTC()
	state.Updated = state.Created
	return col.Insert(state)
}
开发者ID:kyprizel,项目名称:ct_mon,代码行数:27,代码来源:db.go

示例14: Lock

func (s *Schedule) Lock(method string) {
	start := time.Now()
	s.mutex.Lock()
	s.mutexAquired = time.Now()
	s.mutexHolder = method
	s.mutexWaitTime = int64(s.mutexAquired.Sub(start) / time.Millisecond) // remember this so we don't have to call put until we leave the critical section.
}
开发者ID:bridgewell,项目名称:bosun,代码行数:7,代码来源:sched.go

示例15: writePump

func (c *WebConn) writePump() {
	ticker := time.NewTicker(PING_PERIOD)

	defer func() {
		ticker.Stop()
		c.WebSocket.Close()
	}()

	for {
		select {
		case msg, ok := <-c.Send:
			if !ok {
				c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT))
				c.WebSocket.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT))
			if err := c.WebSocket.WriteJSON(msg); err != nil {
				return
			}

		case <-ticker.C:
			c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT))
			if err := c.WebSocket.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
开发者ID:lfbrock,项目名称:platform,代码行数:30,代码来源:web_conn.go


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