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

前端 未结 7 1330
臣服心动
臣服心动 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:00

    There is a simple alternative that does not require any external dependencies:

    defmodule MyApp.Periodically do
      use GenServer
    
      def start_link do
        GenServer.start_link(__MODULE__, %{})
      end
    
      def init(state) do
        schedule_work() # Schedule work to be performed at some point
        {:ok, state}
      end
    
      def handle_info(:work, state) do
        # Do the work you desire here
        schedule_work() # Reschedule once more
        {:noreply, state}
      end
    
      defp schedule_work() do
        Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
      end
    end
    

    Now in your supervision tree:

    worker(MyApp.Periodically, [])
    

提交回复
热议问题