[go] 用ticker定时器来替代循环任务

使用 time.Ticker 来定期执行检查,间隔可以根据需求调整(例如每秒检查一次)。

go 复制代码
package main

import (
    "fmt"
    "sync"
    "time"
)

var (
    gDeviceList= make(map[string]int)
    mu            sync.Mutex
    maxCheckCount = 30
)

func main() {
    // 模拟数据插入
    gDeviceList["device1"] = 0
    gDeviceList["device2"] = 0

    // 使用 goroutine 在后台处理
    go monitorDevices()

    // 模拟其他工作
    time.Sleep(5 * time.Second)

    // 打印最后剩余的设备
    mu.Lock()
    for udid, count := range gDeviceList{
        fmt.Printf("UDID: %s, Count: %d\n", udid, count)
    }
    mu.Unlock()
}

func monitorDevices() {
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()

    for range ticker.C {
        mu.Lock()
        for udid, count := range gDeviceList{
            gDeviceList[udid] = count + 1

            if count > maxCheckCount {
                delete(gDeviceList, udid)
            }
        }
        mu.Unlock()
    }
}
相关推荐
紧跟先前的步伐11 小时前
Go AI Agent 实战 08|HTTP 模型 API 的工作原理与请求流程
人工智能·http·ai·golang
紧跟先前的步伐11 小时前
Go AI Agent 实战 07|模型幻觉、能力边界与成本控制
大数据·人工智能·golang
利威尔xu14 小时前
Go GMP 调度器 10 个高频追问:3 个线上故障让 P99 从 80ms 飙到 2s、10 万 goroutine 泄漏
开发语言·后端·面试·性能优化·golang
FfHUCisI15 小时前
无锁 Reactor 网络模型与 gnet / evio 架构拆解
服务器·开发语言·后端·golang
紧跟先前的步伐1 天前
Go AI Agent 实战 05|Temperature 与生成参数:让模型输出可控
java·人工智能·golang
浮尘笔记1 天前
我用 Go 写了个手机端「远程 AI 开发控制台」(开源)
人工智能·智能手机·golang
microrain1 天前
专业版守核心,企业版做增量:SagooIoT 的跨模块能力出口
物联网·架构·golang·sagooiot
紧跟先前的步伐2 天前
Go AI Agent 实战 04|Prompt 与消息角色:System、User、Assistant
人工智能·golang·prompt
念何架构之路2 天前
go-grpc逻辑架构图
开发语言·后端·golang
FfHUCisI2 天前
Linux 网络 IO 模型演进与 Epoll 内部机制
golang