Launch a script with Porcelain in a Mix.task

Hello,

I have created a mix Task to start a Plug/Cowboy local HTTP server. I would like the user to enter:

mix tasky.start

this command will launch an HTTP local server on port 4000. but I would like to to run it in background - it means that when the user enter this command - it will not block his console. How will you process to create this command ?

My idea was to build the command like this :

def run(argv) do
        with {opts, []} <- parse_opts(argv),
            (port = (opts[:port]) && opts[:port] || @default_port) ## if opts[:port] exists take the value else default_port
        do
            if opts[:foreground] do
                Plug.Adapters.Cowboy.http(Router, [], port: port)
                :timer.sleep(:infinity)

            else
                Porcelain.spawn("elixir --detached -S mix tasky.start --foreground --port=port", [])
            end
        else
            error ->
                IO.inspect error, label: "error"
        end
    end

This doesn’t work - i have this error : ** (Porcelain.UsageError) Looks like the :porcelain app is not running. Make sure you've added :porcelain to the list of applications in your mix.exs.

So if you have a better idea to proceed this command, i am fully buyer :stuck_out_tongue: or i you know why i got this error, it will be great too.

Thanks in advance.

You can start :porcelain with: https://hexdocs.pm/elixir/Application.html#ensure_all_started/2

1 Like

ok thanks - i don’t have the error anymore :slight_smile: but it didn’t work as expected - my local server is not live in background with the code above

“elixir --detached -S mix tasky.start --foreground --port=port”

think you want:

“elixir --detached -S mix tasky.start --foreground --port=#{port}