brain/src/dev/elixir/genserver.md

58 lines
1.1 KiB
Markdown
Raw Normal View History

2019-10-23 11:24:26 +00:00
# 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
2020-08-10 07:15:46 +00:00
# Exec job on continue, then reschedule
2019-10-23 11:24:26 +00:00
def handle_continue(:work, state) do
{:noreply, work_then_reschedule(state)}
end
2020-08-10 07:15:46 +00:00
# Handle info and pass it to continue
2019-10-23 11:24:26 +00:00
def handle_info(:work, state) do
2020-08-10 07:15:46 +00:00
{:noreply, state, {:continue, :work}}
2019-10-23 11:24:26 +00:00
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>}
```