Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Created September 18, 2017 21:18
Show Gist options
  • Save akramsaouri/cacd418dd4371de525fa40599d528fe3 to your computer and use it in GitHub Desktop.
Save akramsaouri/cacd418dd4371de525fa40599d528fe3 to your computer and use it in GitHub Desktop.
Pomodoro implementation using go routines/channels.
package main
import (
"fmt"
"os"
"time"
)
type Pomodoro struct {
turnChan, shortBreakChan, longBreakChan, exit chan bool
turns, max int
debug bool
}
func (p *Pomodoro) start(debug bool) {
p.turnChan = make(chan bool)
p.shortBreakChan = make(chan bool)
p.longBreakChan = make(chan bool)
p.exit = make(chan bool)
p.turns = 0
p.max = 5
p.debug = debug
go p.startPomodoro()
go p.startListener()
}
func (p *Pomodoro) startPomodoro() {
p.notify("pomodoro", "started")
if p.debug {
time.Sleep(time.Second * 5)
} else {
time.Sleep(time.Minute * 25)
}
p.notify("pomodoro", "stopped")
p.turnChan <- true
}
func (p *Pomodoro) startShortBreak() {
p.notify("short break", "started")
if p.debug {
time.Sleep(time.Second * 1)
} else {
time.Sleep(time.Minute * 5)
}
p.notify("short break", "stopped")
p.shortBreakChan <- true
}
func (p *Pomodoro) startLongBreak() {
p.notify("long break", "started")
if p.debug {
time.Sleep(time.Second * 3)
} else {
time.Sleep(time.Minute * 15)
}
p.notify("long break", "stopped")
p.longBreakChan <- true
}
func (p *Pomodoro) startListener() {
for {
select {
case <-p.turnChan:
if p.turns < p.max {
p.turns++
go p.startShortBreak()
} else {
go p.startLongBreak()
}
case <-p.shortBreakChan:
go p.startPomodoro()
case <-p.longBreakChan:
choice := p.promptForRepeat()
if choice == "y" {
p.start(p.debug)
} else {
p.exit <- true
}
}
}
}
func (p *Pomodoro) promptForRepeat() string {
fmt.Println("repeat ? y/n")
var input string
fmt.Scanln(&input)
return input
}
func (p *Pomodoro) notify(step, state string) {
// eg: short break started
// TODO: mac os notifications
fmt.Println(step + " " + state)
}
func main() {
var debug bool
// work with small duration values on debug mode
if len(os.Args) >= 2 && os.Args[1] == "--debug" {
debug = true
}
pomodoro := Pomodoro{}
pomodoro.start(debug)
<-pomodoro.exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment