0

Im trying to simply get this Erlang program to print out a value periodically and I'm using this module to do so:

   -module(hot).
   -export([start/0,handle_info/2,  add/1]).

   start() ->
           Num = 0,
           timer:send_interval(1000, interval),
           {ok, Num}.

   handle_info(interval, Num) ->
          erlang:display(0),
          {noreply, Num}.

   add(X) ->
          X+2.

I'm referencing one of the answers from this post

I also tried using a modification from the top answer as follows:

init([]) ->
  Timer = erlang:send_after(1, self(), check),
  {ok, Timer}.

handle_info(check, OldTimer) ->
  erlang:cancel_timer(OldTimer),
  erlang:display(0),
  Timer = erlang:send_after(1000, self(), check),
  {noreply, Timer}.

Nothing prints out in either case. It just tells me something like {ok,<0.43.0>}. It seems that handle_info is never called at all.

Community
  • 1
  • 1
Khaines0625
  • 387
  • 1
  • 5
  • 17
  • of course. It would be better if you write what you are doing (which functions call) and what you expect to see on the display. –  Apr 17 '16 at 23:08
  • erlang:display(0). Just display 0. At this point it doesnt matter what it is, its just an experiment. I just call init() or start(). – Khaines0625 Apr 17 '16 at 23:16
  • You misunderstood me, I want to know what you want to get as a result. handle_info - is used for the handling of spontaneous messages in gen_server OTP. You have to process the message received from the timer. –  Apr 17 '16 at 23:23
  • I'm brand new to Erlang and I must just not understand whats going on here. Ultimately all I want is for a value to be printed onto the screen every second. Perhaps this is the entirely wrong approach? The message itself isn't something I really care about, it will always be the same message--display a value to the screen. – Khaines0625 Apr 17 '16 at 23:29
  • I just badly know English, so I want to make sure that the correctly understood the problem before answering. –  Apr 17 '16 at 23:34

1 Answers1

4

Show the value of every second you can, for example, as follows:

-module(test).
-export([start/1]).

start(Num) when not is_number(Num)-> {error,not_a_number};
start(Num)->spawn(fun()->print(Num) end).

print(Num)->
    erlang:start_timer(1000, self(), []),
    receive
          {timeout, Tref, _} ->
            erlang:cancel_timer(Tref),
            io:format("~p~n",[Num]),
            if
                Num =:=0 -> io:format("Stop~n");
                true -> print(Num-1)
            end
    end.

For information about this function and its arguments, you can read the documentation. Such a method is more effecient than the use of the timer module.