假设我想每4小时发送一堆电子邮件或重新创建站点地图或其他东西,我在凤凰城或只有Elixir如何做到这一点?
当前回答
除了使用过程。Send_after,您还可以使用:timer.apply_interval。
其他回答
您可以使用erlcron。你使用它就像
job = {{:weekly, :thu, {2, :am}},
{:io, :fwrite, ["It's 2 Thursday morning~n"]}}
:erlcron.cron(job)
作业是一个2元素元组。第一个元素是表示作业进度的元组,第二个元素是函数或MFA(Module、function、Arity)。在上面的例子中,我们运行:io。fwrite(“现在是周四凌晨2点”),每周四凌晨2点。
希望有帮助!
有一个简单的替代方案,不需要任何外部依赖:
defmodule MyApp.Periodically do
use GenServer
def start_link(_opts) 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
现在在你们的监督树中:
children = [
MyApp.Periodically
]
Supervisor.start_link(children, strategy: :one_for_one)
Crontab lib &:timer, send_after, GenState机器或GenServer。
通常我们在elixir模块中定义cron表达式,然后在init期间在该模块中解析。 https://hexdocs.pm/crontab/readme.html
我们使用这个来安排一个计时器。 Process.send_after(self(),:消息,时间) 或者:timer.send_interval / 2 它返回计时器ref,它可以存储在state中,也可以被ref取消。
通常我们使用Oban来实现这一点,但这取决于任务的优先级。 如果您只想运行一个应该在特定时间段后运行的作业。那么你也可以使用Genserver。
Genservers在应用程序启动时启动。你可以使用周期进程Process.send_after(self(),:work, time)和添加handle_info来处理你想做的工作。当我需要向我的项目添加长轮询时,我使用了这个。
Quantum允许您在运行时创建、查找和删除作业。
此外,您可以在创建cronjob时将参数传递给任务函数,如果不满意UTC,甚至可以修改时区。
如果你的应用程序是作为多个独立实例运行的(例如Heroku),有PostgreSQL或Redis支持的作业处理器,它们也支持任务调度:
奥班:https://github.com/sorentwo/oban
Exq: https://github.com/akira/exq
Toniq: https://github.com/joakimk/toniq
Verk: https://github.com/edgurgel/verk