Skip to content

Commit

Permalink
Change API so it works when a midnight boundary is crossed.
Browse files Browse the repository at this point in the history
  • Loading branch information
d11wtq committed Apr 2, 2013
1 parent 4269646 commit 7d01f1d
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 61 deletions.
2 changes: 1 addition & 1 deletion Emakefile
@@ -1,4 +1,4 @@
%% Erlang Makefile for the reminders app
%% Erlang Makefile for the wake-app.

{'src/*', [debug_info,
{i, "src"},
Expand Down
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -12,9 +12,9 @@ I currently use it to start the radio playing for an hour each morning.

``` erlang
% Start playing SBS Radio 2 at 8am every morning, until 9am.
{ok, Pid} = daily_event:start_link("open 'radium://tune-in/?h=&b=sbs&c=2&'",
{ok, Pid} = daily_task:start_link("open 'radium://tune-in/?h=&b=sbs&c=2&'",
{8,0,0},
{9,0,0}).
3600).
```

## License & Copyright
Expand Down
58 changes: 0 additions & 58 deletions src/daily_event.erl

This file was deleted.

61 changes: 61 additions & 0 deletions src/daily_task.erl
@@ -0,0 +1,61 @@
%% @doc Runs a command at the same time every day.

-module(daily_task).

-export([start/3,
start_link/3]).

-record(task, {cmd,
start_at,
duration=60000,
state=wait}).

%% -- public api

%% @doc Start the task server standalone.
%%
%% @spec start(Cmd, {H,M,S}, Duration) -> {ok, Pid}.
%% @spec start("say 'Wakey Wakey!'", {6,0,0}, 30) -> {ok, Pid}.
start(Cmd, Start = {_, _, _}, Duration) ->
{ok, spawn(fun() -> loop(make_task(Cmd, Start, Duration)) end)}.

%% @doc Start the task server.
%%
%% Cmd is the shell command to run.
%% {H,M,S} represents the time at which it should run.
%% Duration is the number of seconds the task should run for.
%%
%% @spec start_link(Cmd, {H,M,S}, Duration) -> {ok, Pid}.
%% @spec start_link("say 'Wakey Wakey!'", {6,0,0}, 30) -> {ok, Pid}.
start_link(Cmd, Start = {_, _, _}, Duration) ->
{ok, spawn_link(fun() -> loop(make_task(Cmd, Start, Duration)) end)}.

%% -- private api

loop(Task = #task{state=wait}) ->
case within_run_window(calendar:local_time(), Task) of
true ->
io:format("Running `~s'~n", [Task#task.cmd]),
os:cmd(Task#task.cmd),
loop(Task#task{state=running});
false ->
timer:sleep(1000),
loop(Task)
end;
loop(Task = #task{state=running}) ->
case within_run_window(calendar:local_time(), Task) of
true ->
timer:sleep(1000),
loop(Task);
false ->
io:format("Stopping `~s'~n", [Task#task.cmd]),
loop(Task#task{state=wait})
end.

make_task(Cmd, {H,M,S}, Duration) ->
#task{cmd=Cmd, state=wait, start_at={H,M,S}, duration=Duration}.

within_run_window({Date, Time}, #task{start_at={H, M, S}, duration=Duration}) ->
Now = calendar:datetime_to_gregorian_seconds({Date, Time}),
Start = calendar:datetime_to_gregorian_seconds({Date, {H, M, S}}),
Now >= Start andalso Now < Start + Duration.

0 comments on commit 7d01f1d

Please sign in to comment.