Function 在Erlang中是否可以有持续动作?
我想在特定的时间间隔内执行一个函数,我的意思是:Function 在Erlang中是否可以有持续动作?,function,timer,erlang,Function,Timer,Erlang,我想在特定的时间间隔内执行一个函数,我的意思是: action()-> ... ... move(2) for 3 sec. %hypothetical example where it's executed each sec. 我想我可以做到这一点: action() -> ... ... move(2), sleep(1), move(2), sleep(1), move(2). 但是,我想知道是否有其他方法来实现它,因为我查看了计时器模块,但没有找到任何可以使用的方
action()->
...
...
move(2) for 3 sec. %hypothetical example where it's executed each sec.
我想我可以做到这一点:
action() ->
...
...
move(2),
sleep(1),
move(2),
sleep(1),
move(2).
但是,我想知道是否有其他方法来实现它,因为我查看了计时器模块,但没有找到任何可以使用的方法
谢谢大家! 递归就是您要寻找的 要快速回答您的问题,请执行以下操作:
action(0)->
done;
action(Count)->
io:format("moved"),
sleep(1000),
action(Count - 1).
要使某些东西有用:
action()->
Pid = spawn(fun()->start_moving(3) end),
sleep(10),
exit(Pid, terminate).
start_moving(0)->
done;
start_moving(Count)->
io:format("moved a little"),
sleep(1000),
start_moving(Count -1).
您需要根据您的应用程序对此进行改进,下面是一个您可以很好地控制间隔任务的示例:
action()->
Ref = make_ref(),
Count = 3,
Interval = 1000,
Pid = spawn(fun()->start_moving(Ref, Count, Interval) end),
%do lots of stuff
sleep(10000)
% stop moving
Pid ! {Ref, stop}.
start_moving(Ref, Interval, 0)->
done;
start_moving(Ref, Interval, Count)->
receive
{Ref, stop}->
ok;
_->
start_moving(Ref, Interval, Count)
after
Interval->
io:format("moving"),
start_moving(Ref, Interval, Count - 1)
end.
递归就是你要找的 要快速回答您的问题,请执行以下操作:
action(0)->
done;
action(Count)->
io:format("moved"),
sleep(1000),
action(Count - 1).
要使某些东西有用:
action()->
Pid = spawn(fun()->start_moving(3) end),
sleep(10),
exit(Pid, terminate).
start_moving(0)->
done;
start_moving(Count)->
io:format("moved a little"),
sleep(1000),
start_moving(Count -1).
您需要根据您的应用程序对此进行改进,下面是一个您可以很好地控制间隔任务的示例:
action()->
Ref = make_ref(),
Count = 3,
Interval = 1000,
Pid = spawn(fun()->start_moving(Ref, Count, Interval) end),
%do lots of stuff
sleep(10000)
% stop moving
Pid ! {Ref, stop}.
start_moving(Ref, Interval, 0)->
done;
start_moving(Ref, Interval, Count)->
receive
{Ref, stop}->
ok;
_->
start_moving(Ref, Interval, Count)
after
Interval->
io:format("moving"),
start_moving(Ref, Interval, Count - 1)
end.
如果您不想睡觉,只想一直调用函数直到时间过去,您可以使用以下方法:
execute_while(Fun, N)->
execute_while(Fun, N, timer:tc(Fun)).
execute_while(Fun, N, {Time, _Value}) when N>=Time ->
{Time2, Value2} = timer:tc(Fun),
execute_while(Fun, N, {Time + Time2, Value2});
execute_while(_, _, R) ->
R.
这样说吧:
execute_while(fun()-> move() end, 1000).
如果您不想睡觉,只想一直调用函数直到时间过去,您可以使用以下方法:
execute_while(Fun, N)->
execute_while(Fun, N, timer:tc(Fun)).
execute_while(Fun, N, {Time, _Value}) when N>=Time ->
{Time2, Value2} = timer:tc(Fun),
execute_while(Fun, N, {Time + Time2, Value2});
execute_while(_, _, R) ->
R.
这样说吧:
execute_while(fun()-> move() end, 1000).
我把答案编辑了1000次,对不起。我把答案编辑了1000次,对不起。