Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created December 9, 2025 21:49
Show Gist options
  • Select an option

  • Save Micrified/c73d882825615a9be0547ce4832a6d1e to your computer and use it in GitHub Desktop.

Select an option

Save Micrified/c73d882825615a9be0547ce4832a6d1e to your computer and use it in GitHub Desktop.
Synchronised Task Completion
package main
import (
"fmt"
"time"
"sync"
"sort"
)
type task struct {
name string
duration time.Duration
}
func (t task) exec () {
start := time.Now()
fmt.Printf("%s: %s - Starting ...\n", start.Format("15:04:05"), t.name)
time.Sleep(t.duration * time.Second)
end := time.Now()
fmt.Printf("%s: %s - Ended!\n", end.Format("15:04:05"), t.name)
}
func schedule(ts []task) {
if len(ts) > 0 {
var wg sync.WaitGroup
var i int
sort.Slice(ts, func(i, j int) bool {
return ts[i].duration > ts[j].duration
})
fmt.Println(ts)
wg.Go(func(){ ts[0].exec() })
for i = 1; i < len(ts); i++ {
time.Sleep((ts[i-1].duration - ts[i].duration) * time.Second)
t := ts[i];
wg.Go(func(){ t.exec() })
}
time.Sleep(ts[i-1].duration * time.Second)
wg.Wait()
}
}
func main() {
tasks := []task {
{"A", 2},
{"B", 1},
{"C", 2},
{"D", 5},
}
fmt.Println(tasks)
schedule(tasks)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment