Sobes.tech
Junior — Middle

Can you explain the mechanism of asynchronous and preemptive tasks in systems?

sobes.tech AI

Answer from AI

In systems, asynchronous tasks refer to operations that are executed in parallel with the main thread without blocking it. Scheduled tasks are tasks planned to be executed at a specific time or with a certain periodicity.

In Go, goroutines are often used for asynchronous operations — lightweight threads launched with the go keyword before a function call. To schedule tasks, you can use timers or third-party libraries, such as time.Ticker for periodic tasks.

Example of an asynchronous task with a goroutine:

func asyncTask() {
    fmt.Println("Asynchronous task is running")
}

func main() {
    go asyncTask() // run asynchronously
    // main thread continues to work
    time.Sleep(time.Second) // wait for the goroutine to finish
}

For scheduling tasks:

func scheduledTask() {
    fmt.Println("Scheduled task")
}

func main() {
    ticker := time.NewTicker(2 * time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-ticker.C:
            scheduledTask()
        }
    }
}
Can you explain the mechanism of asynchronous and… - sobes.tech