f3aef60debad4a2a8f19611e001ef9dd9ce1fba8
[project/libubox.git] / examples / uloop-example.lua
1 #!/usr/bin/env lua
2
3 local socket = require "socket"
4
5 local uloop = require("uloop")
6 uloop.init()
7
8 local udp = socket.udp()
9 udp:settimeout(0)
10 udp:setsockname('*', 8080)
11
12 -- timer example 1 (will run repeatedly)
13 local timer
14 function t()
15 print("1000 ms timer run");
16 timer:set(1000)
17 end
18 timer = uloop.timer(t)
19 timer:set(1000)
20
21 -- timer example 2 (will run once)
22 uloop.timer(function() print("2000 ms timer run"); end, 2000)
23
24 -- timer example 3 (will never run)
25 uloop.timer(function() print("3000 ms timer run"); end, 3000):cancel()
26
27 -- periodic interval timer
28 local intv
29 intv = uloop.interval(function()
30 print(string.format("Interval expiration #%d - %dms until next expiration",
31 intv:expirations(), intv:remaining()))
32
33 -- after 5 expirations, lower interval to 500ms
34 if intv:expirations() >= 5 then
35 intv:set(500)
36 end
37
38 -- cancel after 10 expirations
39 if intv:expirations() >= 10 then
40 intv:cancel()
41 end
42 end, 1000)
43
44 -- process
45 function p1(r)
46 print("Process 1 completed")
47 print(r)
48 end
49
50 function p2(r)
51 print("Process 2 completed")
52 print(r)
53 end
54
55 uloop.timer(
56 function()
57 uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=1"}, p1)
58 end, 1000
59 )
60 uloop.timer(
61 function()
62 uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=2"}, p2)
63 end, 2000
64 )
65
66 -- Keep udp_ev reference, events will be gc'd, even if the callback is still referenced
67 -- .delete will manually untrack.
68 udp_ev = uloop.fd_add(udp, function(ufd, events)
69 local words, msg_or_ip, port_or_nil = ufd:receivefrom()
70 print('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words)
71 if words == "Stop!" then
72 udp_ev:delete()
73 end
74 end, uloop.ULOOP_READ)
75
76 udp_count = 0
77 udp_send_timer = uloop.timer(
78 function()
79 local s = socket.udp()
80 local words
81 if udp_count > 3 then
82 words = "Stop!"
83 udp_send_timer:cancel()
84 else
85 words = 'Hello!'
86 udp_send_timer:set(1000)
87 end
88 print('Send UDP packet to 127.0.0.1:8080 :'..words)
89 s:sendto(words, '127.0.0.1', 8080)
90 s:close()
91
92 udp_count = udp_count + 1
93 end, 3000
94 )
95
96 uloop.run()
97