How can I schedule code to run every few hours in Elixir or Phoenix framework?

前端 未结 7 1293
臣服心动
臣服心动 2020-11-29 14:21

So let\'s say I want to send a bunch of emails or recreate sitemap or whatever every 4 hours, how would I do that in Phoenix or just with Elixir?

相关标签:
7条回答
  • 2020-11-29 15:24

    I find :timer.send_interval/2 slightly more ergonomic to use with a GenServer than Process.send_after/4 (used in the accepted answer).

    Instead of having to reschedule your notification each time you handle it, :timer.send_interval/2 sets up an interval on which you receive a message endlessly—no need to keep calling schedule_work() like the accepted answer uses.

    defmodule CountingServer do
      use GenServer
    
      def init(_) do
        :timer.send_interval(1000, :update)
        {:ok, 1}
      end
    
      def handle_info(:update, count) do
        IO.puts(count)
        {:noreply, count + 1}
      end
    end
    

    Every 1000 ms (i.e., once a second), IntervalServer.handle_info/2 will be called, print the current count, and update the GenServer's state (count + 1), giving you output like:

    1
    2
    3
    4
    [etc.]
    
    0 讨论(0)
提交回复
热议问题