使用 --sup
建立一個含有 supervision tree 的空專案,這會幫我們產生相 application.ex
檔案
mix new nice_bank --sup
.
├── README.md
├── lib
│ ├── nice_bank
│ │ └── application.ex
│ └── nice_bank.ex
├── mix.exs
└── test
├── nice_bank_test.exs
└── test_helper.exs
打開 lib/nice_bank/application.ex
defmodule NiceBank.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: NiceBank.Worker.start_link(arg)
# {NiceBank.Worker, arg}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: NiceBank.Supervisor]
Supervisor.start_link(children, opts)
end
end
可以看到 start 函式已經有 Supervisor.start_link
供我們直接使用
當然在使用之前,要先將我們的 Bank module 放入這個專案,可以放在
lib/nice_bank/bank.ex
並依照資料夾結構將 module 名稱改為 NiceBank.Bank
在 start 函數裡的 children list 加入 NiceBank.Bank
def start(_type, _args) do
children = [
{NiceBank.Bank, 100}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: NiceBank.Supervisor]
Supervisor.start_link(children, opts)
end
如此一來,當我們執行這個 mix 時就會一起啟動,如 iex -S mix
/nice_bank$iex -S mix
Erlang/OTP 27 [erts-15.0.1] [source] [64-bit] [smp:10:10] [ds:10:10:10] [async-threads:1] [jit]
Compiling 3 files (.ex)
Generated nice_bank app
啟動中
開戶存了 0 元。
Interactive Elixir (1.17.2) - press Ctrl+C to exit (type h() ENTER for help)
時間到了,該算利息了
時間到了,該算利息了
時間到了,該算利息了