Last active
April 7, 2016 06:53
-
-
Save Hajto/693df8d5f84adea7763d527e0a7e8efd to your computer and use it in GitHub Desktop.
Elixir Deadlock, don't ever try to the same thing.
This file contains hidden or 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
defmodule TwitchSniper.GiveawayManager do | |
use GenServer | |
require Logger | |
def start_link do | |
GenServer.start_link(__MODULE__, :ok, name: __MODULE__) | |
end | |
def new_giveaway(item) do | |
GenServer.cast(__MODULE__, {:new_item, item}) | |
end | |
def get_first do | |
GenServer.call(__MODULE__, {:get_first} ) | |
end | |
def cycle do | |
GenServer.call(__MODULE__, {:cycle} ) | |
end | |
def start_cycling do | |
Process.send_after(__MODULE__, {:time_trigger} , get_first.delay) | |
end | |
def start_cycling(delay) do | |
Process.send_after(__MODULE__, { :time_trigger }, delay) | |
end | |
##ServerSide Callback | |
def init(:ok) do | |
{:ok, :queue.new } | |
end | |
def handle_call({:get_first}, _from, state) do | |
{:reply, :queue.get(state) , state} | |
end | |
def handle_call({ :cycle }, _from, state) do | |
{ {_,_}, new_queue} = :queue.out(state) | |
new_item = :queue.get(new_queue) | |
IO.inspect "New first item delay #{new_item.delay}" | |
start_cycling(new_item.delay) | |
{:reply, new_item, new_queue } | |
end | |
def handle_cast({:new_item, giveaway}, state) do | |
{:noreply, :queue.in(giveaway, state)} | |
end | |
def handle_info({:time_trigger}, _state)do | |
Logger.info "Starting cycle" | |
cycle | |
end | |
def handle_info( message, _) do | |
Logger.error message | |
end | |
# def terminate(_reason, _state) do | |
# flush | |
# end | |
end |
This file contains hidden or 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
defmodule TwitchSniper.GiveawayManagerTest do | |
use ExUnit.Case | |
alias TwitchSniper.Giveaway | |
alias TwitchSniper.GiveawayManager | |
test "Add 2 giveaways and cycle them" do | |
giveaway_one = %Giveaway{organiser: "Asshole", product: "A very pc Game", delay: 200} | |
giveaway_two = %Giveaway{organiser: "Not an asshole", product: "A Console", delay: 200} | |
GiveawayManager.new_giveaway(giveaway_one) | |
GiveawayManager.new_giveaway(giveaway_two) | |
assert GiveawayManager.get_first == giveaway_one | |
GiveawayManager.start_cycling | |
:timer.sleep(giveaway_one.delay + 10) | |
assert GiveawayManager.get_first == giveaway_two | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment