如何安排代码在Elixir或Phoenix框架中每隔几个小时运行一次? [英] How can I schedule code to run every few hours in Elixir or Phoenix framework?
本文介绍了如何安排代码在Elixir或Phoenix框架中每隔几个小时运行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,假设我想每隔4个小时发送一堆电子邮件或重新创建站点地图或其他内容,我将如何在Phoenix或仅使用Elixir做到这一点?
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?
推荐答案
有一个简单的替代方法,不需要任何外部依赖项:
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
现在在您的监督树中:
worker(MyApp.Periodically, [])
这篇关于如何安排代码在Elixir或Phoenix框架中每隔几个小时运行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文