Background Tasks, Scheduler & Emails

Everything here works without Redis. The queue and the scheduler state live in their own SQLite files under app/data/ (lila_tasks.db, lila_system.db), separate from your database, so they never lock it and also work when your project uses MySQL or PostgreSQL.

1. Task queue

app/tasks.py
# app/tasks.py  (import it from main.py)
from lila.core.tasks import task

@task(retries=3, timeout=120, backoff=5)
async def send_invoice(order_id: int):
    ...

@task
def resize_avatar(path: str):          # sync functions run in a thread
    ...

# anywhere (a route, another task...)
await send_invoice.delay(order_id=42)              # as soon as possible
await send_invoice.delay(order_id=42, _in=600)     # in 10 minutes

Who runs the tasks?

By default every web worker consumes the queue in the background (TASKS_IN_PROCESS=true, TASK_CONCURRENCY=2). For heavy jobs run a dedicated process and set TASKS_IN_PROCESS=false:

Terminal
lila worker --driver sqlite -c 4      # dedicated consumer (systemd: lila deploy --with-worker)
lila tasks stats                      # queued: 3  running: 1  done: 120  dead: 1
lila tasks list --status dead
lila tasks retry 57
lila tasks purge --status done

With CACHE_DRIVER=redis, lila worker keeps consuming the Redis queue used by BackgroundTask; --driver sqlite forces the SQLite queue.

2. Scheduled jobs

app/jobs.py
from lila.core.scheduler import every, cron

@every(minutes=10)
async def refresh_exchange_rates(): ...

@cron("0 3 * * *")                    # every day at 03:00 (server local time)
def nightly_cleanup(): ...

@cron("*/15 9-18 * * mon-fri", queue=True)   # hand the run to the task queue (retries)
async def sync_crm(): ...

@every(hours=1, run_on_start=True)
async def warm_cache(): ...
Terminal
lila schedule list                      # jobs, schedule, last run and status
lila schedule run nightly_cleanup       # run one now

3. Emails with Jinja templates

resources/html/emails/welcome.jinja
{# resources/html/emails/welcome.jinja #}
{% extends "emails/base.jinja" %}
{% set subject = translate['welcome'] ~ ", " ~ name %}
{% block content %}
  <p>Hi {{ name }},</p>
  <p>Your account is ready.</p>
  {% set button_url = app_url ~ "/dashboard" %}{% set button_text = "Open dashboard" %}
  {% include "emails/button.jinja" %}
{% endblock %}
Python
from lila.core.mailer import Mailer

await Mailer.send_template("ana@example.com", "welcome", {"name": "Ana"})               # now
task_id = await Mailer.send_template("ana@example.com", "welcome", {"name": "Ana"}, queue=True)  # via the queue
subject, html, text = Mailer.render_template("welcome", {"name": "Ana"}, lang="es")      # preview / tests