v2 / vlib / x / async / examples / periodic.v
49 lines · 44 sloc · 803 bytes · 15fb60b77ea6073658aa8355b247f2e1ae03b714
Raw
1import context
2import time
3import x.async as xasync
4
5fn main() {
6 ctx, cancel := xasync.with_cancel()
7 ticks := chan int{cap: 4}
8 done := chan string{cap: 1}
9
10 worker := spawn fn [ctx, ticks, done] () {
11 xasync.every(ctx, 10 * time.millisecond, fn [ticks] (mut ctx context.Context) ! {
12 _ = ctx
13 ticks <- 1
14 }) or {
15 done <- err.msg()
16 return
17 }
18 done <- 'completed'
19 }()
20
21 if !wait_tick(ticks) || !wait_tick(ticks) {
22 eprintln('periodic job did not tick')
23 exit(1)
24 }
25 cancel()
26
27 select {
28 msg := <-done {
29 println('periodic stopped: ${msg}')
30 }
31 1 * time.second {
32 eprintln('periodic job did not stop')
33 exit(1)
34 }
35 }
36 worker.wait()
37}
38
39fn wait_tick(ticks chan int) bool {
40 select {
41 _ := <-ticks {
42 return true
43 }
44 1 * time.second {
45 return false
46 }
47 }
48 return false
49}
50