2 回答

TA貢獻(xiàn)1810條經(jīng)驗 獲得超4個贊
實現(xiàn)此目的的一種方法是利用 for/select 超時習(xí)語,有幾種類似的方法可以做到這一點。舉個簡單的例子:
package main
import (
"fmt"
"time"
)
func main() {
abort := make(chan struct{})
go func() {
for {
select {
case <-abort:
return
case <-time.After(1 * time.Second):
// replace fmt.Println() with the command you wish to run
fmt.Println("tick")
}
}
}()
// replace time.Sleep() with code waiting for 'abort' command input
time.Sleep(10 * time.Second)
abort <- struct{}{}
}
要修改此示例以在您的情況下工作,請將您要運行的代碼放在<-time.After():案例中,如果在此期間沒有其他案例可接收,則該案例(在此實例中)將每秒運行一次。而不是time.Sleep()我放在最后的代碼,而是放置將中斷<-time.After():案例的代碼, <- struct{}{}在abort通道上發(fā)送(或任何你命名的)。
注意:在這個答案的早期版本中,我中止了一個chan bool,因為我喜歡它的清晰性<-abort true并且不認(rèn)為 chan struct{}它很清晰,但是我選擇在這個例子中改變它,因為<- struct{}{}不清楚,特別是一旦你已經(jīng)習(xí)慣了這種模式。
此外,如果您希望命令在 for 循環(huán)的每次迭代中執(zhí)行并且不等待超時,那么您可以設(shè)置 case default:, remove<-time.After()并且它將在另一個通道尚未準(zhǔn)備好接收的循環(huán)的每次迭代中運行。
如果您愿意,您可以在操場上使用此示例,盡管它不允許系統(tǒng)調(diào)用或default:案例示例在該環(huán)境中運行。

TA貢獻(xiàn)1842條經(jīng)驗 獲得超21個贊
在不睡覺的情況下一遍又一遍地運行它:
func run(stop <-chan struct{}) {
ps := exec.Command("ps")
for {
select {
case <-stop:
return
default:
ps.Run()
//processing the output
}
}
}
然后go run(stop)。并每 3 秒運行一次(例如):
func run(stop <-chan struct{}) {
ps := exec.Command("ps")
tk := time.Tick(time.Second * 3)
for {
select {
case <-stop:
return
case <-tk:
ps.Run()
//processing the output
}
}
}
- 2 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報