当前位置:网站首页>golang中的定时器
golang中的定时器
2022-06-12 10:18:00 【love666666shen】
在golang程序中,可以使用crontab进行定时任务处理,也可以通过Timer或Ticker简单地进行定时任务设置。
Timer和Ticker定时器的区别为:
使用Timer定时器时,需要调用Reset方法对定时器事件进行重置;而Ticker定时不需要调用Reset。
Timer定时任务示例:
func process() {
interval := 6 * time.Second
timer := time.NewTimer(interval)
ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
// 定时任务处理逻辑
processLogic()
for {
// 调用Reset方法对timer对象进行定时器重置
timer.Reset(interval)
select {
case <-ctx.Done():
// 超时处理
log.Info("process timeout, exit")
return
case <-timer.C:
// 定时任务处理逻辑
processLogic()
}
}
}
Ticker定时任务,不需要Reset重置定时器。Ticker定时任务示例如下:
......
ticker := time.NewTicker(time.Second)
ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
for {
select {
case <-ticker.C:
// 定时任务处理逻辑
...
case <-ctx.Done():
fmt.Println("request timeout")
// 结束定时任务
return
}
}
......
边栏推荐
- Basic use of scratch
- spark_ sql
- [926. flip the string to monotonic increment]
- Li Yang, a scientific and technological innovator and CIO of the world's top 500 group: the success of digital transformation depends on people. Decision makers should always focus on "firewood"
- Spark complex structure data retrieval method
- Why is cross-border e-commerce so popular? Papaya mobile takes you to find out
- Web3.0与数字时尚,该如何落地?
- Yarn scheduling
- Create simple windowing programs using Visual Studio 2017
- Tp6 debugging (trace)
猜你喜欢

极速搭建元宇宙画廊 #oncyber.io

Autojs learning notes 6:text (txt) Findone() will report an error when switching apps. Finally, solve the implementation effect and switch any app until the script finds the control with the specified

Raw socket usage

Dynamic proxy
![[Mozilla] basic concept analysis of IPDL](/img/b2/97b4db069052133ee614ecb1a8369e.jpg)
[Mozilla] basic concept analysis of IPDL

【MySQL】sql_ Model mode

FPGA VGA display based on de2-115 platform

Transport layer protocol -- TCP protocol

远程桌面不能复制粘贴解决办法

Implementation principle of redisson distributed lock
随机推荐
[untitled]
How high can C language reach by self-study alone?
1268_FreeRTOS任务上下文切换的实现
One test for twoorthree years, recording some thoughts on test exchange experience
Dynamic proxy
[chromium] location information kernel debugging
GNU EFI development environment settings
[Wayland] Weston startup process analysis
93. 獲得內網的所有IP地址
CLAHE in opencv for 16 bit image enhancement display
一测两三年,记测试交流经验的一些感想
Value investment
1268_ Implementation of FreeRTOS task context switching
机器学习之数据处理与可视化【鸢尾花数据分类|特征属性比较】
机器学习不是你想用,想用就能用
[DDS] dds-rpc implementation based on opendds
Papaya Mobile has a comprehensive layout of cross-border e-commerce SaaS papaya orange. What are the opportunities for this new track?
【ParquetEncodingException: empty fields are illegal, the field should be ommited completely instead
不需要安装防毒软件的系统Chromebook
在App内跳转微信,打开微信