Add elixir genserver example
This commit is contained in:
parent
9c4668ae6e
commit
50d46d7daf
3 changed files with 60 additions and 0 deletions
|
@ -6,6 +6,8 @@
|
||||||
|
|
||||||
- [Golang](./dev/golang/main.md)
|
- [Golang](./dev/golang/main.md)
|
||||||
- [Testing](./dev/golang/testing.md)
|
- [Testing](./dev/golang/testing.md)
|
||||||
|
- [Elixir](./dev/elixir/main.md)
|
||||||
|
- [GenServer](./dev/elixir/genserver.md)
|
||||||
- [Rust](./dev/rust/main.md)
|
- [Rust](./dev/rust/main.md)
|
||||||
- [serde](./dev/rust/serde.md)
|
- [serde](./dev/rust/serde.md)
|
||||||
- [Testing](./dev/rust/testing.md)
|
- [Testing](./dev/rust/testing.md)
|
||||||
|
|
57
src/dev/elixir/genserver.md
Normal file
57
src/dev/elixir/genserver.md
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
# GenServer
|
||||||
|
|
||||||
|
## How to create a scheduled job (kudos [href](https://github.com/hrefhref))
|
||||||
|
|
||||||
|
### Code
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
defmodule Jobs do
|
||||||
|
# Jobs module is based on GenServer
|
||||||
|
use GenServer
|
||||||
|
|
||||||
|
# Init with `init` as initial value, then continue
|
||||||
|
def init(init) do
|
||||||
|
# call to handle_continue
|
||||||
|
{:ok, init, {:continue, :work}}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Exec the job for the first time, at the end of init
|
||||||
|
def handle_continue(:work, state) do
|
||||||
|
{:noreply, work_then_reschedule(state)}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Exec the job when :work message is received
|
||||||
|
def handle_info(:work, state) do
|
||||||
|
{:noreply, work_then_reschedule(state)}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Get timer from config.exs
|
||||||
|
def get_timer_config() do
|
||||||
|
{:ok, timer} = Application.fetch_env(:app, :timer)
|
||||||
|
timer
|
||||||
|
end
|
||||||
|
|
||||||
|
# Do the important stuff
|
||||||
|
defp work_then_reschedule(state) do
|
||||||
|
# Modify state
|
||||||
|
state = state + 1
|
||||||
|
|
||||||
|
IO.puts(state)
|
||||||
|
IO.puts("Work, then reschedule !")
|
||||||
|
|
||||||
|
# Reschedule, later
|
||||||
|
Process.send_after(self(), :work, get_timer_config() * 1000)
|
||||||
|
|
||||||
|
# Return updated state
|
||||||
|
state
|
||||||
|
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
```iex
|
||||||
|
iex> {:ok, pid} = GenServer.start_link(Jobs, 1)
|
||||||
|
{:ok, #PID<0.251.0>}
|
||||||
|
```
|
1
src/dev/elixir/main.md
Normal file
1
src/dev/elixir/main.md
Normal file
|
@ -0,0 +1 @@
|
||||||
|
# Elixir
|
Loading…
Reference in a new issue