1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paiza.ioでelixirAdvent Calendar 2022

Day 11

paiza.ioでelixir その61

Last updated at Posted at 2022-11-11

概要

paiza.ioでelixirやってみた。
DateTime.now使ってみた。

サンプルコード

defmodule Tsk0 do
	def tick(agent, interval \\ 50) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		{:ok, datetime} = DateTime.now("Etc/UTC")
		IO.puts("task0 #{datetime}")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end
defmodule Tsk1 do
	def tick(agent, interval \\ 100) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		{:ok, datetime} = DateTime.now("Etc/UTC")
		IO.puts("task1 #{datetime}")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end
defmodule Tsk2 do
	def tick(agent, interval \\ 200) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		{:ok, datetime} = DateTime.now("Etc/UTC")
		IO.puts("task2 #{datetime}")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end

Tsk0.start(Foo) 
|> IO.inspect
Tsk1.start(Foo1) 
|> IO.inspect
Tsk2.start(Foo2) 
|> IO.inspect
Task.async(fn -> 
	Tsk0.tick(Foo) 
end) 
Task.async(fn -> 
	Tsk1.tick(Foo1) 
end) 
Task.async(fn -> 
	Tsk2.tick(Foo2) 
end) 
:timer.sleep(300)



実行結果

{:ok, #PID<0.101.0>}
{:ok, #PID<0.102.0>}
{:ok, #PID<0.103.0>}
task1 2022-11-10 22:17:31.029618Z
task0 2022-11-10 22:17:31.029618Z
task2 2022-11-10 22:17:31.029624Z
task0 2022-11-10 22:17:31.083142Z
task1 2022-11-10 22:17:31.133214Z
task0 2022-11-10 22:17:31.134161Z
task0 2022-11-10 22:17:31.185162Z
task2 2022-11-10 22:17:31.233134Z
task1 2022-11-10 22:17:31.234136Z
task0 2022-11-10 22:17:31.236105Z
task0 2022-11-10 22:17:31.287162Z
task1 2022-11-10 22:17:31.336007Z
task0 2022-11-10 22:17:31.339882Z

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?