[erlang-questions] About erlang:statistics/1 and timeout values

Oscar Hellström oscar@REDACTED
Fri Apr 24 19:05:38 CEST 2009


Per Melin wrote:
> Oscar Hellström:
>   
>> back to (part of) the original question, how would we go about
>> decrementing a timeout value between blocking calls. I could use now
>> diffs, or erlang:start_timer/3... are there better ways?
>>     
>
> Can it really be simpler than now_diff/2?
>
> loop(Timeout) when Timeout > 0 ->
>     Before = now(),
>     receive
>         X ->
>             % Do whatever
>             loop(Timeout - timer:now_diff(now(), Before) div 1000)
>     after Timeout ->
>        loop(0)
>     end;
> loop(_) ->
>     timeout.
>
> (If I needed millisecond precision I would do it a little different
> just to be sure.)
>   
It could be, and it could avoid being affected by time changes on your
machine.

do_x(Timeout) ->
    TRef = erlang:start_timer(Timeout),
    loop(TRef, Timeout).
loop(_, false) ->
    timeout;
loop(TRef, Timeout) ->
    receive
        X ->
            case done(X) of
                true   -> ok;
                false -> loop(TRef, erlang:read_timer(TRef))
    after Timeout  -> timeout
    end.

It could also be done with a counter counting up... which might be better?

Cheers

-- 
Oscar Hellström, oscar@REDACTED
Office: +44 20 7655 0337
Mobile: +44 798 45 44 773
Erlang Training and Consulting Ltd
http://www.erlang-consulting.com/




More information about the erlang-questions mailing list