Last active
February 5, 2020 06:52
-
-
Save iantbutler01/ecb51bf78198007287b66817f901287f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CrawlerExample.Queue do | |
use GenServer | |
#client | |
def start_link(opts \\ []) do | |
GenServer.start_link(__MODULE__, nil, opts) | |
end | |
def load_from_file(file_path) do | |
GenServer.cast(__MODULE__, {:load_state_from_disk, file_path}) | |
end | |
#server | |
@impl true | |
def init(_init_arg) do | |
schedule_write_to_disk(5000) | |
{:ok, :queue.new} | |
end | |
@impl true | |
def handle_info(:schedule_write_to_disk, state) do | |
current_state = :queue.to_list(state) | |
state_json = Poison.encode!(current_state) | |
File.write("/tmp/crawler_state.json", state_json) | |
schedule_write_to_disk(interval) | |
end | |
@impl true | |
def handle_cast({:load_state_from_disk, file_path}, _) do | |
contents = File.read!(file_path) | |
from_json = Poison.decode!(contents) | |
{:noreply, :queue.from_list(from_json)} | |
end | |
defp schedule_write_to_disk(interval), do: :erlang.send_after(interval, self(), :schedule_write_to_disk) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment