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 21

paiza.ioでelixir その21

Last updated at Posted at 2022-10-28

概要

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

参考にしたページ

サンプルコード


defmodule Counter.Server do
	use GenServer
	require Logger
	def start_link(current_number) do
        Logger.info "ok"
		GenServer.start_link(__MODULE__, current_number, name: __MODULE__)
	end
	def count_up do
		GenServer.call __MODULE__, :up
	end
	def count_down do
		GenServer.cast __MODULE__, :down
	end
	def current_number do
		GenServer.call __MODULE__, :current
	end
	def handle_call(:up, _from, current_number) do
		{:reply, current_number + 1, current_number + 1}
	end
	def handle_call(:current, _from, current_number) do
		{:reply, current_number, current_number}
	end
	def handle_cast(:down, current_number) do
		{:noreply, current_number - 1}
	end
	def kill do
		Logger.info "ok2"
		pid = Process.whereis(__MODULE__)
		Process.exit(pid, :kill)
	end
end

defmodule Counter.Supervisor do
	use Supervisor
	def start_link(arg) do
		Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
	end
	def init(_) do
		children = [{Counter.Server, 0}]
		Supervisor.init(children, strategy: :one_for_one)
	end
end

Counter.Supervisor.start_link([])
|> IO.inspect
Counter.Server.current_number
|> IO.inspect
Counter.Server.count_up
|> IO.inspect
Counter.Server.count_up
|> IO.inspect
Counter.Server.kill
|> IO.inspect
:timer.sleep(100)
Counter.Server.current_number
|> IO.inspect
Counter.Server.count_up
|> IO.inspect



実行結果

10:12:16.472 [info]  ok
{:ok, #PID<0.99.0>}
0
1
2
true

10:12:16.477 [info]  ok2

10:12:16.477 [info]  ok
0
1

成果物

以上。

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?