本文整理汇总了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
}
示例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()
}
示例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
}
示例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)
}
}
}
示例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
}
示例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)})
}
示例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")
}
示例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(),
},
})
}
}
示例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
}
示例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
}
示例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")
}
}
示例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)
}
示例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)
}
示例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.
}
示例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
}
}
}
}