简体   繁体   中英

Populate ETS table on application start

I am trying to create an elixir/erlang ets table and populate it with some data on application start. I see that it is run when started, but may be compile/runtime error?

For example:

def start(_type, _args) do
  import Supervisor.Spec

  # Define workers and child supervisors to be supervised
  children = [
    DataToETS,
  ]

  opts = [strategy: :one_for_one, name: App.Supervisor]
  Supervisor.start_link(children, opts)
end

And then the DataToETS :

defmodule DataToETS do
  use Task

  def start_link(opts) do
    Task.start_link(DataToETS, :run, [])
  end

  def run do
    # Load to the ETS  
  end

end

In my DataToETS I do log and it logs. Any idea how to populate and then access when application runs?

If you simply want to create a table and populate it once (without attachment to another sub-process, like GenServer ), you can just directly do it in the start/2 callback of your application:

def start(_type, _args) do
   # Create ETS Table here
   # and seed it with initial data

   # Other stuff...
end

If you want to do it exclusively when a sub-process is started, you can create/populate it in it's init/1 callback. This is how it would look like for a GenServer:

defmodule DataToETS do
  def start_link(_args) do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def init(:ok) do
    # Create ETS Table here
    # and seed it with initial data
    :ok
  end
end

It would be similar for other processes like Supervisor, Task, GenStage, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM