How to run the Elixir app?

What is the correct way to run an Elixir application?

I am creating a simple project:

mix new app 

and after that I can do:

 mix run 

which basically compiles my application once. Therefore, when I add:

 IO.puts "running" 

in lib/app.ex I see "running" only for the first time, each successive run does nothing unless some changes occur. What can I do the generated app.app ?

Of course, I know that I can:

 escript: [main_module: App] 

in mix.exs , specify def main(args): and then:

 mix escript.build ./app 

but it is, in my opinion, cumbersome.

There is also something like:

 elixir lib/app.exs 

but that does not mean mix.exs , obviously what is needed for dependencies in my app .

+55
elixir
Jun 06 '15 at 21:33
source share
2 answers

mix run launches your application. Just when you just put IO.puts "something" in a file, this line is evaluated only at compile time, it does nothing at runtime. If you want something to start when the application starts, you need to specify it in mix.exs .

Usually you need an entry-level Application that will be launched. To do this, add the mod option to mix.exs :

 def application do [ # this is the name of any module implementing the Application behaviour mod: {NewMix, []}, applications: [:logger]] end 

And then in this module you need to implement a callback that will be called when the application starts:

 defmodule NewMix do use Application def start(_type, _args) do IO.puts "starting" # some more stuff end end 

The start callback should actually set up your top-level root directory or control tree, but in this case you will already see that it is called every time you use mix run , although it is followed by an error.

 def start(_type, _args) do IO.puts "starting" Task.start(fn -> :timer.sleep(1000); IO.puts("done sleeping") end) end 

In this case, we start a simple process in our callback that just sleeps for one second and then outputs something - this is enough to satisfy the start callback API, but we don’t see "done sleeping" . The reason for this is that by default mix run will exit after the callback completes. To avoid this, you need to use mix run --no-halt - in this case, the VM will not be stopped.

Another useful way to launch your application is iex -S mix - this will behave similarly to mix run --no-halt , but also open the iex shell where you can interact with your code and the running application.

+67
Jun 07 '15 at 0:29
source share

You can run tasks by importing Mix.Task into your module instead of mix run .

I think this one is what you are looking for.

Alternatively, instead of mix <task.run> you can simply run mix to run the default task. Just add default_task: "bot.run" to the def project do [..] end mix.exs in mix.exs . Contact here .

+5
Jan 24 '16 at 2:31 on
source share



All Articles