I would hope to execute the "weekly updated" before "daily check" as follows. That means "time.Time" should put "timeChan" immediately rather than do it after waiting for over two seconds when the main function Start running.
And the result should be like this
weekly updated
daily check
daily check
daily check
daily check
weekly updated
daily check
daily check
daily check
daily check
...
Of course,i can just print "weekly updated" firstly one time, but there is have an elegant method?
The code is as follows
package main
import "time"
import "fmt"
func main() {
var a int
timeChan := time.NewTicker(time.Second * 2).C
tickChan := time.NewTicker(time.Millisecond * 500).C
for {
select {
case <-timeChan:
fmt.Println("weekly updated")
a = 1
case <-tickChan:
if a == 1 {
fmt.Println("daily check")
} else {
fmt.Println("Not update?")
}
}
}
}
The result is as follows
Not update?
Not update?
Not update?
weekly updated
daily check
daily check
daily check
daily check
weekly updated
daily check
daily check
daily check
daily check
...
Set your Ticker for weekly
at first time.Millisecond
. Then change it, when 1st time it is done.
package main
import (
"fmt"
"time"
)
func main() {
var a = 0
ticker := time.NewTicker(1)
timeChan := ticker.C
tickChan := time.NewTicker(time.Millisecond * 500).C
for {
select {
case <-timeChan:
fmt.Println("weekly updated")
if a == 0 {
ticker.Stop()
timeChan = time.NewTicker(time.Second * 2).C
}
a = 1
case <-tickChan:
if a == 1 {
fmt.Println("daily check")
} else {
fmt.Println("Not update?")
}
default:
}
}
}
Output:
weekly updated
daily check
daily check
daily check
daily check
weekly updated
Just put the work in a function and call it.
var a int
timeChan := time.NewTicker(time.Second * 2).C
tickChan := time.NewTicker(time.Millisecond * 500).C
f := func() {
fmt.Println("weekly updated")
a = 1
}
f()
for {
select {
case <-timeChan:
f()
case <-tickChan:
if a == 1 {
fmt.Println("daily check")
} else {
fmt.Println("Not update?")
}
}
}