[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()
    }
}
相关推荐
roman_日积跬步-终至千里1 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
海奥华29 小时前
go中的接口返回设计思想
开发语言·后端·golang
飞川撸码13 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
roman_日积跬步-终至千里21 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang
孔令飞1 天前
Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践
ai·云原生·容器·golang·kubernetes
我的golang之路果然有问题1 天前
云服务器部署Gin+gorm 项目 demo
运维·服务器·后端·学习·golang·gin
孔令飞1 天前
Go 为何天生适合云原生?
ai·云原生·容器·golang·kubernetes
YGGP1 天前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
march of Time1 天前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone