|
| 1 | +defmodule Backend.Files.FileProcess do |
| 2 | + use GenServer, restart: :temporary |
| 3 | + alias Backend.Files |
| 4 | + |
| 5 | + @timeout 5_000 # Время бездействия (например, 5 секунд) |
| 6 | + |
| 7 | + # API |
| 8 | + def start_link(file_id) do |
| 9 | + GenServer.start_link(__MODULE__, file_id, name: via_tuple(file_id)) |
| 10 | + end |
| 11 | + |
| 12 | + def update_content(file_id, new_content) do |
| 13 | + GenServer.call(via_tuple(file_id), {:update_content, new_content}) |
| 14 | + end |
| 15 | + |
| 16 | + defp via_tuple(file_id) do |
| 17 | + {:via, Registry, {Backend.Files.FileRegistry, file_id}} |
| 18 | + end |
| 19 | + |
| 20 | + # Callbacks |
| 21 | + def init(file_id) do |
| 22 | + file = Files.get_file(file_id) # Загружаем файл из БД при запуске |
| 23 | + {:ok, %{file: file, timer: reset_timer(nil)}} |
| 24 | + end |
| 25 | + |
| 26 | + def handle_call({:update_content, new_content}, _from, %{file: file, timer: timer} = state) do |
| 27 | + new_file = %{file | content: new_content} |
| 28 | + {:reply, :ok, %{state | file: new_file, timer: reset_timer(timer)}} |
| 29 | + end |
| 30 | + |
| 31 | + def handle_info(:timeout, %{file: file} = state) do |
| 32 | + IO.inspect file |
| 33 | + Files.save_file(file) # Сохраняем в БД перед завершением |
| 34 | + {:stop, :normal, state} |
| 35 | + end |
| 36 | + |
| 37 | + defp reset_timer(timer) do |
| 38 | + # Отменяем старый таймер, если он существует |
| 39 | + if timer, do: Process.cancel_timer(timer) |
| 40 | + # Устанавливаем новый таймер |
| 41 | + Process.send_after(self(), :timeout, @timeout) |
| 42 | + end |
| 43 | +end |
0 commit comments