Skip to content

Instantly share code, notes, and snippets.

@iand
Last active January 4, 2016 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iand/8558610 to your computer and use it in GitHub Desktop.
Save iand/8558610 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Test interrupt nonsense")
fmt.Println("Run the functiona and allow to run on")
NewInterruptableTimer(1*time.Second, tFunc1, "fred")
time.Sleep(2 * time.Second)
fmt.Println("That test timed-out... this should be interrupted...")
interruption1 := NewInterruptableTimer(1*time.Second, tFunc1, "barney")
time.Sleep(100 * time.Millisecond)
interruption1 <- 2
time.Sleep(2 * time.Second)
fmt.Println("That test was interrupted... no try one that is aborted...")
interruption2 := NewInterruptableTimer(1*time.Second, tFunc1, "elma")
time.Sleep(100 * time.Millisecond)
interruption2 <- -911
time.Sleep(2 * time.Second)
}
type InterruptableTimer struct {
*time.Timer
}
func NewInterruptableTimer(d time.Duration, f func(interface{}, int) interface{}, data interface{}) chan int {
interrupt := make(chan int, 0)
t := &InterruptableTimer{}
t.Timer = time.AfterFunc(d, func() { f(data, -1) })
go func() {
flag := <-interrupt
t.Timer.Stop()
if flag > -911 {
f(data, flag)
} else {
fmt.Printf("Aborted with code: %d\n", flag)
}
}()
return interrupt
}
// TEST FUNC -
func tFunc1(d interface{}, i int) interface{} {
if i == 0 {
fmt.Printf("Timed out... %d\n", i)
} else if i <= -911 {
fmt.Printf("Aborted... %d\n", i)
return "Aborted"
} else {
fmt.Printf("Was interrupted %d\n", i)
}
return "Completed "
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment