πŸ› 
Background Tasks and Jobs

Once off background tasks

When you just want to run some code in a background task then you can use PetalPro.BackgroundTask.run/1:
1
PetalPro.BackgroundTask.run(fn ->
2
do_some_time_instensive_stuff()
3
end)
Copied!
This can be useful for speeding up responses in a HTTP request or LiveView action - you delegate anything that takes time to a background task (eg sending emails, sending to Slack, creating a log, etc.). Since we want to respond to a user request as soon as possible, you run these other non-essential tasks in a background task and it won't hold up the response.

Background jobs with Oban

A background job is a something you want to run outside of a normal HTTP request/response cycle. Things like sending weekly emails or processing images. We use Oban for this.
A background job is performed by a "worker". Each worker gets its own file. Petal Pro comes with an example worker you can duplicate:
1
defmodule PetalPro.Workers.ExampleWorker do
2
@moduledoc """
3
Example of how to do async work with Oban.
4
​
5
Run with:
6
Oban.insert(PetalPro.Workers.ExampleWorker.new(%{}))
7
"""
8
use Oban.Worker, queue: :default
9
require Logger
10
​
11
@impl Oban.Worker
12
def perform(%Oban.Job{} = _job) do
13
today = Timex.now() |> Timex.to_date()
14
Logger.info("ExampleWorker: Today is #{today}")
15
:ok
16
end
17
end
Copied!
You can run this worker by inserting a job into the database:
1
Oban.insert(PetalPro.Workers.ExampleWorker.new(%{}))
Copied!
Once in the database, Oban will try running the task and retry it if it fails. You can see any failed jobs by checking the database:
Oban jobs show up in the "oban_jobs" table
Jobs that have been completed are deleted every 24 hours so your database won't swell over time.

Cron jobs

You can tell your workers to work at certain times with Oban's CRON functionality. See the examples in config.exs:
1
config :petal_pro, Oban,
2
repo: PetalPro.Repo,
3
queues: [default: 5],
4
plugins: [
5
{Oban.Plugins.Pruner, max_age: (3600 * 24)},
6
{Oban.Plugins.Cron,
7
crontab: [
8
{"@daily", PetalPro.Workers.ExampleWorker}
9
# {"* * * * *", PetalPro.EveryMinuteWorker},
10
# {"0 * * * *", PetalPro.EveryHourWorker},
11
# {"0 */6 * * *", PetalPro.EverySixHoursWorker},
12
# {"0 0 * * SUN", PetalPro.EverySundayWorker},
13
# More examples: https://crontab.guru/examples.html
14
]}
15
]
Copied!
​
​