方式:根据erlang:send_after 启动个定时器,在gen_server 里面实现它。
直接上个测试代码:
在init初始化的时候,启动个timer,间隔时间为3秒 并输出打印 。
defmodule Distro.Cron do use GenServer require Logger def start_link() do # GenServer.start_link(__MODULE__, %{callback_function: callback_function}, name: __MODULE__) GenServer.start_link(__MODULE__, %{}, name: __MODULE__) end def reset_timer() do GenServer.call(__MODULE__, :reset_timer) end def init(state) do timer = Process.send_after(self(), :work, 3000) {:ok, %{timer: timer}} end def handle_call(:reset_timer, _from, %{timer: timer}) do :timer.cancel(timer) timer = Process.send_after(self(), :work, 3000) {:reply, :ok, %{timer: timer}} end def handle_info(:work, _state) do # Do the work you desire here # Start the timer again timer = Process.send_after(self(), :work, 3000) timestamp = timestamp() # Logger.debug "handle_info 111111" Logger.info("Print unixtimeStamp: #{timestamp}") {:noreply, %{timer: timer}} end # So that unhanded messages don't error def handle_info(_, state) do {:ok, state} end # 获取当前时间戳 def timestamp() do {m,s,_} = :erlang.timestamp() m * 1000000 + s end end