[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()
    }
}
相关推荐
_小许_6 小时前
Go语言的io输入输出流
golang
白总Server6 小时前
MySQL在大数据场景应用
大数据·开发语言·数据库·后端·mysql·golang·php
好兄弟给我起把狙7 小时前
[Golang] Select
开发语言·后端·golang
GoppViper17 小时前
golang学习笔记28——golang中实现多态与面向对象
笔记·后端·学习·golang·多态·面向对象
Python私教17 小时前
Go语言现代web开发14 协程和管道
开发语言·前端·golang
楚钧艾克17 小时前
Windows系统通过部署wsl + Goland进行跨平台开发
linux·windows·后端·ubuntu·golang
__AtYou__17 小时前
Golang | Leetcode Golang题解之第413题等差数列划分
leetcode·golang·题解
编程点滴17 小时前
go单测报错 monkey undefined jmpToFunctionValue
开发语言·后端·golang
__AtYou__1 天前
Golang | Leetcode Golang题解之第405题数字转换为十六进制数
leetcode·golang·题解
吃着火锅x唱着歌1 天前
Go语言设计与实现 学习笔记 第七章 内存管理(1)
笔记·学习·golang