Skip to content

Commit edd49a6

Browse files
authored
Merge pull request mouredev#2799 from boterop/15-async
#15 - elixir
2 parents 2197e35 + afa4713 commit edd49a6

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
defmodule Boterop.Asynchrony do
2+
@spec timer(seconds :: integer()) :: Task.t()
3+
def timer(seconds) do
4+
Task.async(fn ->
5+
for count <- 1..seconds do
6+
:timer.sleep(995)
7+
IO.inspect(count)
8+
end
9+
end)
10+
end
11+
12+
@spec async_func(name :: String.t(), seconds :: integer()) :: Task.t()
13+
def async_func(name, seconds) do
14+
Task.async(fn ->
15+
print_start(name, seconds)
16+
:timer.sleep(seconds * 1000)
17+
print_end(name)
18+
end)
19+
end
20+
21+
@spec a() :: Task.t()
22+
def a() do
23+
name = "A"
24+
seconds = 1
25+
26+
Task.async(fn ->
27+
print_start(name, seconds)
28+
29+
:timer.sleep(seconds * 1000)
30+
print_end(name)
31+
end)
32+
end
33+
34+
@spec b() :: Task.t()
35+
def b() do
36+
name = "B"
37+
seconds = 2
38+
39+
Task.async(fn ->
40+
print_start(name, seconds)
41+
42+
:timer.sleep(seconds * 1000)
43+
print_end(name)
44+
end)
45+
end
46+
47+
@spec c() :: Task.t()
48+
def c() do
49+
name = "C"
50+
seconds = 3
51+
52+
Task.async(fn ->
53+
print_start(name, seconds)
54+
55+
:timer.sleep(seconds * 1000)
56+
print_end(name)
57+
end)
58+
end
59+
60+
@spec d(on_complete_list :: list(Task.t())) :: Task.t()
61+
def d(on_complete_list) do
62+
wait_for(on_complete_list)
63+
64+
Task.async(fn ->
65+
name = "D"
66+
seconds = 1
67+
68+
print_start(name, seconds)
69+
70+
:timer.sleep(seconds * 1000)
71+
print_end(name)
72+
end)
73+
end
74+
75+
@spec print_start(name :: String.t(), seconds :: integer()) :: String.t()
76+
defp print_start(name, seconds), do: IO.inspect("Starting #{name} (#{seconds} sec)")
77+
78+
@spec print_end(name :: String.t()) :: String.t()
79+
defp print_end(name), do: IO.inspect("#{name} has finished")
80+
81+
@spec wait_for(list(Task.t())) :: term()
82+
defp wait_for([]), do: nil
83+
84+
defp wait_for([head | tail]) do
85+
Task.await(head)
86+
wait_for(tail)
87+
end
88+
end
89+
90+
timer = Boterop.Asynchrony.timer(15)
91+
92+
Boterop.Asynchrony.async_func("Task 1", 10)
93+
a = Boterop.Asynchrony.a()
94+
b = Boterop.Asynchrony.b()
95+
c = Boterop.Asynchrony.c()
96+
Boterop.Asynchrony.d([a, b, c])
97+
98+
Task.await(timer, 20000)

0 commit comments

Comments
 (0)