Last active
January 4, 2016 02:59
-
-
Save iand/8558610 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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