代码之家  ›  专栏  ›  技术社区  ›  Pete J

在应用程序启动时填充ETS表

  •  0
  • Pete J  · 技术社区  · 7 年前

    ets 并在应用程序启动时用一些数据填充它。我看到它在启动时运行,但可能是编译/运行时错误?

    例如:

    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
    

    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
    

    我做日志和它日志。知道应用程序运行时如何填充和访问吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Sheharyar    7 年前

    如果您只想创建一个表并填充一次 (不附加到另一个子流程,如 GenServer ),您可以直接在 start/2 应用程序的回调:

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

    您可以在它的 init/1

    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