Phoenix应用程序中的自定义混合任务

Vas*_*ich 3 elixir phoenix-framework

当我在我的凤凰应用程序中运行自定义混合任务(我认为它甚至不与凤凰相关但仍然)使用一些外部库(例如https://github.com/knrz/geocoder)我得到

** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
    :erlang.send(:geocoder_workers, {:"$gen_cast", {:cancel_waiting, #Reference<0.0.1.13074>}}, [:noconnect])
Run Code Online (Sandbox Code Playgroud)

直到我添加

Application.ensure_all_started(:geocoder)

混合任务.所以我的问题是为什么我的所有依赖项都不会自动启动?是我做错了什么?

Dog*_*ert 10

您是对的,默认情况下,在Mix任务中不会启动应用程序的依赖项.它们需要手动启动.启动所有应用程序依赖项的最简单方法是调用Mix.Task.run("app.start")(或者Application.ensure_all_started(:my_app)如果Mix不可用).这样,mix.exs如果文件中列出的所有应用程序尚未运行,它们将会启动.

这是在Phoenix Framework站点的" 混合任务"页面末尾附近记录的:

如果要使新的混合任务使用应用程序的基础结构,则需要确保在执行混合任务时启动应用程序.如果您需要从混合任务中访问数据库,这将特别有用.谢天谢地,mix让我们很容易:

def run(_args) do
  Mix.Task.run "app.start"
  Mix.shell.info "Now I have access to Repo and other goodies!"
  ...
end
Run Code Online (Sandbox Code Playgroud)