Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Erlang timed out processing


May 13, 2021 Erlang


Table of contents


Erlang timed out processing

Before we improve the messager program, let's learn some basic principles together. R ecall that when "ping" ends, it sends a message to "pong" with an atomic value finished to notify "pong" to end the program. A nother way to end "pong" is to exit the program when "pong" does not receive a message from "ping" for a certain period of time. W e can add a time-out to pong to implement it:

-module(tut19).

-export([start_ping/1, start_pong/0,  ping/2, pong/0]).

ping(0, Pong_Node) ->
    io:format("ping finished~n", []);

ping(N, Pong_Node) ->
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).

pong() ->
    receive
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    after 5000 ->
            io:format("Pong timed out~n", [])
    end.

start_pong() ->
    register(pong, spawn(tut19, pong, [])).

start_ping(Pong_Node) ->
    spawn(tut19, ping, [3, Pong_Node]).

Compile the above code and copy the resulting tut19.beam file to a directory, and here is the output pong@kosken node:

true
Pong received ping
Pong received ping
Pong received ping
Pong timed out

The output on ping@gollum node is:

(ping@gollum)1> tut19:start_ping(pong@kosken).
<0.36.0>
Ping received pong
Ping received pong
Ping received pong
ping finished 

time-out is set at:

pong() ->
    receive
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    after 5000 ->
            io:format("Pong timed out~n", [])
    end.

When recieve is executed, the time-out timer (5000 ms) starts, and the time-out timer is canceled as soon as it receives a message for .ping, Ping_PID. I f you don't receive a Ping_PID," the program that follows time-out is executed after 5000 milliseconds. A fter must be the last in recieve, that is, all other messages in recieve receive processing over time-out messages. I f there is a function that returns a value of integer values, we can call the function after after to set its return value to a time-out value, as follows:

after pong_timeout() ->

In general, there are many better ways to implement monitoring in addition to using timeouts to monitor the divisions of a distributed Erlang system. T imeouts are useful for monitoring events from outside the system, for example, when you want to receive messages from an external system within a specified time. For example, we can use timeouts to find that a user has left the messenger system, for example, when the user has not accessed the system for 10 minutes, and thinks that he or she has left the system.