DEV Community

Artem Piskun
Artem Piskun

Posted on

4 1

Simple golang jobber with ttl

There are some points where you need TTL to do something, i.e. API Request or some other restrictions. In golang you could do it in very simple way using goroutines and standart time package.

The basics to solve the task are looked something like this.

// First of all you need a channel to interract with the request
c := make(chan int, 1)

// start anonymous routine with the some function call
go func() {
    result := someFunc()
    c <- result
    close(c)
}()

// start timer
timer := time.NewTimer(<timeout>)
defer timer.Stop()

var result int
var err error
select {
    case result = <-c:
    // do nothing, break select
    case <-timer.C:
    err = fmt.Errorf("time exceeded")
}
// handle error and use the result in the code
Enter fullscreen mode Exit fullscreen mode

And as an example there is a net.LookupIP fuction call from the standart package with a TTL



func main() {
    ips, err := lookupIPs("https://dev.to", time.Second)
    if err != nil {
        // check the error
    }
    // do something with the list of ips
}

type lookupIP struct {
    ips []net.IP
    err error
}

func lookupIPs(url string, timeout time.Duration) ([]net.IP, error) {
    c := make(chan lookupIP, 1)

    go func() {
        ips, err := net.LookupIP(url)
        c <- lookupIP{ips, err}
        close(c)
    }()

    timer := time.NewTimer(timeout)
    defer timer.Stop()

    var lIP lookupIP
    select {
    case lIP = <-c:
        // do nothing, break select
    case <-timer.C:
        lIP.err = fmt.Errorf("lookup ip: time exceeded")
    }
    if lIP.err != nil {
        return nil, lIP.err
    }
    return lIP.ips, nil
}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Retry later