Last active
August 29, 2015 14:23
-
-
Save imetallica/b85598c401456fb553f4 to your computer and use it in GitHub Desktop.
Async task
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
defmodule Alchemy.Time do | |
@author "Iuri L. Machado <[email protected]>" | |
@copyright "2015 .Fix." | |
@license "BSD" | |
use GenServer | |
require Logger | |
@moduledoc """ | |
RFC 1123 Time compatible. It caches time on an ets table that is updated | |
every second and all time API calls come from the cached time, so it | |
provides very fast date/time computations. Based on cowboy. | |
""" | |
def start_link do | |
GenServer.start_link __MODULE__, [] | |
end | |
@doc """ | |
Starts the time process and sets up the ets table. | |
""" | |
def init _args do | |
Logger.info "Initializing Time." | |
:ets.new :time_cache, [:set, :public, :named_table, | |
{:read_concurrency, true}] | |
utc = :erlang.universaltime | |
:ets.insert :time_cache, {:time, utc} | |
Task.async fn -> | |
:erlang.universaltime |> update_internal_time | |
end | |
# spawn(fn -> | |
# :erlang.universaltime |> update_internal_time | |
# end) | |
{:ok, "Time Initialization Done"} | |
end | |
@doc """ | |
Gets current time. | |
""" | |
def get_rfc1123 do | |
GenServer.call __MODULE__, :now | |
end | |
def handle_call :now do | |
time = :ets.lookup :time_cache, :time | |
{:reply, time} | |
end | |
def handle_cast {:update_time, "start"} do | |
:erlang.universaltime |> update_internal_time | |
{:noreply, :ok} | |
end | |
defp update_internal_time utc do # Updates the internal time on ets. | |
:timer.sleep 1000 | |
Logger.info "#{__MODULE__}: Updating internal time." | |
:ets.insert :time_cache, {:time, utc} | |
:erlang.universaltime |> update_internal_time | |
end | |
defp day num do | |
case num do | |
1 -> "Sun" | |
2 -> "Mon" | |
3 -> "Tue" | |
4 -> "Wen" | |
5 -> "Thu" | |
6 -> "Fri" | |
7 -> "Sat" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment