golang 中的定时器(timer),更巧妙的处理timeout
今天看到kite项目中的一段代码,发现挺有意思的。
// generateToken returns a JWT token string. Please see the URL for details:
// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1
func generateToken(aud, username, issuer, privateKey string) (string, error) {
tokenCacheMu.Lock()
defer tokenCacheMu.Unlock() uniqKey := aud + username + issuer // neglect privateKey, its always the same
signed, ok := tokenCache[uniqKey]
if ok {
return signed, nil
} tknID, err := uuid.NewV4()
if err != nil {
return "", errors.New("Server error: Cannot generate a token")
} // Identifies the expiration time after which the JWT MUST NOT be accepted
// for processing.
ttl := TokenTTL // Implementers MAY provide for some small leeway, usually no more than
// a few minutes, to account for clock skew.
leeway := TokenLeeway tkn := jwt.New(jwt.GetSigningMethod("RS256"))
tkn.Claims["iss"] = issuer // Issuer
tkn.Claims["sub"] = username // Subject
tkn.Claims["aud"] = aud // Audience
tkn.Claims["exp"] = time.Now().UTC().Add(ttl).Add(leeway).Unix() // Expiration Time
tkn.Claims["nbf"] = time.Now().UTC().Add(-leeway).Unix() // Not Before
tkn.Claims["iat"] = time.Now().UTC().Unix() // Issued At
tkn.Claims["jti"] = tknID.String() // JWT ID signed, err = tkn.SignedString([]byte(privateKey))
if err != nil {
return "", errors.New("Server error: Cannot generate a token")
} // cache our token
tokenCache[uniqKey] = signed // cache invalidation, because we cache the token in tokenCache we need to
// invalidate it expiration time. This was handled usually within JWT, but
// now we have to do it manually for our own cache.
time.AfterFunc(TokenTTL-TokenLeeway, func() {
tokenCacheMu.Lock()
defer tokenCacheMu.Unlock() delete(tokenCache, uniqKey)
}) return signed, nil
}
这里的 time.AfterFunc 来做token的timeout处理,是我之前都不知道的。
我之前的做法,自己启动一个 单独的 goroutine,对所有的token做遍历,判断是否timeout,timout了就进行删除操作。
看到了这段代码,第一个感觉是很妙,第二个是如果用起来,会不会有啥副作用。
翻看源码:https://golang.org/src/time/sleep.go?h=AfterFunc#L116
// AfterFunc waits for the duration to elapse and then calls f
// in its own goroutine. It returns a Timer that can
// be used to cancel the call using its Stop method.
func AfterFunc(d Duration, f func()) *Timer {
t := &Timer{
r: runtimeTimer{
when: when(d),
f: goFunc,
arg: f,
},
}
startTimer(&t.r)
return t
}
这里的startTimer 是用了系统自身的timer实现,只不过是golang在这里做了一层兼容各个平台的封装,应该是没有什么副作用啦。
// Interface to timers implemented in package runtime.
// Must be in sync with ../runtime/runtime.h:/^struct.Timer$
type runtimeTimer struct {
i int
when int64
period int64
f func(interface{}, uintptr) // NOTE: must not be closure
arg interface{}
seq uintptr
} // when is a helper function for setting the 'when' field of a runtimeTimer.
// It returns what the time will be, in nanoseconds, Duration d in the future.
// If d is negative, it is ignored. If the returned value would be less than
// zero because of an overflow, MaxInt64 is returned.
func when(d Duration) int64 {
if d <= {
return runtimeNano()
}
t := runtimeNano() + int64(d)
if t < {
t = << - // math.MaxInt64
}
return t
} 40 func startTimer(*runtimeTimer)
41 func stopTimer(*runtimeTimer) bool
不得不感慨,原生库还是有很多好东东的,需要自己慢慢发觉。
golang 中的定时器(timer),更巧妙的处理timeout的更多相关文章
- python中实现定时器Timer
实现定时器最简单的办法是就是循环中间嵌time.sleep(seconds), 这里我就不赘述了 # encoding: UTF-8 import threading #Timer(定时器)是Thre ...
- Python--day41--threading中的定时器Timer
定时器Timer:定时开启线程 代码示例: #定时开启线程 import time from threading import Timer def func(): print('时间同步') #1-3 ...
- [ Javascript ] JavaScript中的定时器(Timer) 是怎样工作的!
作为入门者来说.了解JavaScript中timer的工作方式是非常重要的.通常它们的表现行为并非那么地直观,而这是由于它们都处在一个单一线程中.让我们先来看一看三个用来创建以及操作timer的函数. ...
- golang中的定时器
1. timer 定时器,时间到了执行,只执行一次 package main import ( "fmt" "time" ) func main() { // ...
- Java中的定时器Timer
java.util.Timer是一个实用工具类,该类用来调度一个线程,使线程可以在将来某一时刻开始执行. Java的Timer类可以调度一个线程运行一次,或定期运行. java.util.TimerT ...
- 线程中的定时器Timer类
Timer 定时器 几分钟之后执行一个任务. 创建了一个定时器相当于开启了一条线程,TimerTask相当于一个线程的任务.内部使用wait/notify机制来实现的. 用法非常的简单 就足以里面的 ...
- Swoole 中毫秒定时器(Timer)的使用
间隔定时器, tick 定时器会持续触发,直到调用 clear() 清除为止. $timer = Swoole\Timer::tick(3000, function (int $timer_id, $ ...
- 解决windows 服务中定时器timer 定时偶尔失效 问题
最近做个windows 服务,功能是:定时执行一个任务:自动登录到一个网站后,点击相关网面上的按钮button. 在处理的过程中发现定时器老是不定时的失效,失效时间没有规律. 由于刚开始处于测试阶段, ...
- Java中定时器Timer致命缺点(附学习方法)
简介 这篇文章我一直在纠结到底要不要写,不想写一来因为定时器用法比较简单,二来是面试中也不常问.后来还是决定写了主要是想把自己分析问题思路分享给大家,让大家在学习过程中能够参考,学习态度我相信大部分人 ...
随机推荐
- [C++]在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include StdAfx.h”
问题现象:在写好的.cpp文件后,编译报错.提示"你建立的工程使用了预编译功能, cpp最前边要留一行这样的内容:#include "StdAfx.h"问题原因:网上说是 ...
- Bootstrap学习笔记(6)--导航居中
说明:没找到好办法 <div class="row"> <ul class="nav nav-pills col-md-offset-4"&g ...
- php的json校验json-schema
客户端和服务端的http信息传递,采用json几乎成了标配.json格式简单,易于处理,不过由于没有格式规定,无法校验. 好在php有json-schema模块,可以用来验证json是否符合规定的格式 ...
- 继承log4.net的类
using System; using System.Diagnostics; [assembly: log4net.Config.XmlConfigurator(Watch = true)] nam ...
- [未解决]Exception in thread "main" java.lang.IllegalArgumentException: offset (0) + length (8) exceed the capacity of the array: 6
调用这个方法 是报错,未解决 binfo.setTradeAmount(Double.parseDouble(new String(result.getValue(Bytes.toBytes(fami ...
- 【HDU】3622 Bomb Game(2-SAT)
http://acm.hdu.edu.cn/showproblem.php?pid=3622 又是各种逗.. 2-SAT是一种二元约束,每个点可以置于两种状态,但只能处于一种状态,然后图是否有解就是2 ...
- ThinkPHP项目笔记之RBAC(权限)中篇
现在,说说添加权限,权限管理列表 c.添加权限
- hdu 2857:Mirror and Light(计算几何,点关于直线的对称点,求两线段交点坐标)
Mirror and Light Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- 【mysql】windows7 安装 Mysql
From: http://jingyan.baidu.com/article/e52e3615a1128c40c70c5174.html 安装(解压) ZIP Archive版是免安装的.只要解压就行 ...
- 采用std::thread 替换 openmp
内容转换的,具体详见博客:https://cloud.tencent.com/developer/article/1094617 及对应的code:https://github.com/cpuimag ...