I have a LiveView web app and every night outside working hours (ideally at 12PM each night) I want to perform a single action (run a piece of code)
I have a GenServer that starts when the Phoenix App starts. The problem is that the phoenix server will be started at different times during the day and I do not know what time frame to set the scheduler.
To solve the problem (using my current code) I can perform the following:
When the user starts the phoenix app, capture the current day as a date and store it in state. Run the Genserver every hour to check if the day has changed. If the day changed run the code and store the new day in state.
Repeat.
This would work fine but the problem is I don't understand GenServers well enough to store and compare values as described. I figure I might need an agent to pass data around but I'm kind of just guessing.
I read this answer at it seems really clean but I do not know how to integrate the module: https://stackoverflow.com/a/32086769/1152980
My code is below and is based on this: https://stackoverflow.com/a/32097971/1152980
defmodule App.Periodically do
use GenServer
def start_link(_opts) do
GenServer.start_link(__MODULE__, DateTime)
end
def init(state) do
schedule_work(state)
{:ok, state}
end
def handle_info(:work, state) do
IO.inspect state.utc_now
IO.inspect "_____________NEW"
IO.inspect DateTime.utc_now
# When phoenix app starts - store current date
# When Genserver runs.....
# run conditional on stored date with current date
# If they are different THEN RUN CODE
# If they are the same - do nothing
IO.inspect state
schedule_work(state)
{:noreply, state}
end
defp schedule_work(state) do
IO.inspect "test"
Process.send_after(self(), :work, 10000 ) # 1 sec for testing will change to 1 hour
end
end