美文网首页Go语言实践Go
GO 语言超时实现

GO 语言超时实现

作者: Brown_ | 来源:发表于2019-03-27 17:57 被阅读2次

利用select 进行一个超时的处理

package main

import (
    "fmt"
    "log"
    "runtime"
    "sync"
    "aaaaa/script/WeatherCDN/tqt"
    "time"
)

var pushFileName = make(chan string)
var wg = sync.WaitGroup{}
var versionList = []string{"1.0", "1.1", "2.0", "2.1", "2.2", "2.3"}

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    T := time.Now()

    for cityCode, cityName := range tqt.InitCityConf().CityMap {
        wg.Add(1)
        go backUpWeather(cityCode, cityName)
    }

    for i := 0; i < getFileTotal(); i++ {
        wg.Add(1)
        go push()
    }


    select {
    case <-time.After(20 * time.Second):
        log.Println("time out !---------!!!!!!!")
        log.Println(time.Since(T))
        return
    }

    wg.Wait()
    fmt.Println("done")
    log.Println(time.Since(T))
}

func backUpWeather(cityCode string, cityName string) {
    defer wg.Done()
    tqt.NewWeather(cityCode, cityName).PullData(pushFileName, versionList)
}
func push() {
    defer wg.Done()
    tqt.InitPusher().PushFile(<-pushFileName)
}

func getFileTotal() int {
    return tqt.InitCityConf().TotalCity() * len(versionList)
}

相关文章

网友评论

    本文标题:GO 语言超时实现

    本文链接:https://www.haomeiwen.com/subject/lartbqtx.html