Skip to content

Task Scheduling

David Ciulla edited this page Nov 7, 2026 · 1 revision

Task Scheduling

Laravex's task scheduler allows you to define recurring tasks in a fluent, expressive interface instead of writing cron entries on the server. The scheduler is implemented in Laravex.Console.Schedule using an ETS table as its task registry.


Defining Scheduled Tasks

Register tasks in routes/console.ex (or any module loaded at boot). Call Laravex.Console.Schedule.call/3 with a cron expression and a zero-arity function:

# routes/console.ex
defmodule Routes.Console do
  def register do
    alias Laravex.Console.Schedule

    # Run every minute
    Schedule.call("everyMinute", fn ->
      App.Jobs.HeartbeatCheck.dispatch_sync()
    end)

    # Run at midnight daily
    Schedule.call("daily", fn ->
      App.Jobs.PruneStaleTokens.dispatch_sync()
    end)

    # Run every hour
    Schedule.call("hourly", fn ->
      App.Services.Metrics.flush()
    end)

    # Run every Monday at midnight
    Schedule.call("weekly", fn ->
      App.Reports.WeeklyDigest.send()
    end)

    # Custom cron expression (5-field: minute hour day month dow)
    Schedule.call("0 9 * * 1-5", fn ->
      App.Notifications.DailyStandup.notify_team()
    end)
  end
end

Shorthand Expressions

Expression Runs when
"everyMinute" Every minute
"hourly" At :00 of every hour
"daily" At 00:00 every day
"weekly" At 00:00 every Monday

Cron Expressions

Any 5-field cron expression is accepted:

"* * * * *"       # Every minute
"0 * * * *"       # Every hour
"0 0 * * *"       # Daily at midnight
"0 0 * * 0"       # Every Sunday at midnight
"*/5 * * * *"     # Every 5 minutes
"30 8 1,15 * *"   # 8:30 on the 1st and 15th of each month
"0 9 * * 1-5"     # Weekdays at 9:00

Field order: minute hour day-of-month month day-of-week (0=Sunday).


Registering Artisan Commands as Scheduled Tasks

Use Schedule.command/3 to schedule a registered Artisan command by name:

Schedule.command("sanctum:prune-expired", "daily")
Schedule.command("queue:work", "everyMinute", description: "Process queue")

This creates a task whose function calls Laravex.Console.Router.dispatch(name).


Preventing Overlapping Tasks

By default, if a task is still running when the next execution is due, Laravex will run it again concurrently. To prevent this, use the without_overlapping: true option:

Schedule.call("everyMinute", fn ->
  App.Jobs.SlowImport.dispatch_sync()
end, without_overlapping: true)

When without_overlapping: true is set, the scheduler acquires a mutex via the Cache before running the task. If the mutex is already held (a previous run is still executing), the task is skipped for that tick.

Custom Mutex Key and Expiry

The mutex key defaults to "schedule:overlap:{name}" where :name is derived from the task options. Set a custom name or expiry:

Schedule.call("0 * * * *", fn ->
  App.Services.ReportBuilder.build()
end, without_overlapping: true, name: "report-builder", expires_at: 7200)
Option Default Description
without_overlapping false Enable the overlap guard
name Hash of expression Custom mutex key suffix
expires_at 3600 Mutex TTL in seconds (safety release if the process crashes)

Running the Scheduler

Execute due tasks once:

./artisan schedule:run

To run the scheduler from a system cron, add a one-minute cron entry that calls schedule:run:

* * * * * /path/to/app ./artisan schedule:run >> /dev/null 2>&1

schedule:run calls Laravex.Console.Schedule.run/1, which checks every registered task against the current UTC time and invokes any that are due.


Listing Scheduled Tasks

./artisan schedule:list

Outputs a table of every registered task with its expression and description:

Expression               Command / Callback
------------------------------------------------------------
everyMinute              App.Jobs.HeartbeatCheck (dispatch_sync)
daily                    sanctum:prune-expired
0 9 * * 1-5              App.Notifications.DailyStandup (notify_team)

The description column shows:

  1. The :description option if set.
  2. The :command option if set.
  3. Otherwise, the inspected function reference.

Programmatic Access

# List all registered tasks
Laravex.Console.Schedule.all()
# => [%{expression: "daily", fun: #Function<…>, opts: [without_overlapping: true]}, …]

# Check if a task is due right now
Laravex.Console.Schedule.due?("0 9 * * 1-5")

# Check against a specific datetime
Laravex.Console.Schedule.due?("0 9 * * 1-5", :calendar.universal_time())

# Trigger all due tasks manually
Laravex.Console.Schedule.run()

How the Scheduler Works

  1. schedule:run calls Laravex.Console.Schedule.run/0 with the current UTC time (from :calendar.universal_time/0).
  2. For each registered task, due?/2 evaluates whether the expression matches the current minute, hour, day, month, and day-of-week.
  3. Named shorthand expressions ("everyMinute", "hourly", "daily", "weekly") use an ETS deduplication key to ensure they fire at most once per natural period within a single process lifetime.
  4. If without_overlapping: true, a cache mutex is acquired before the task runs and released in the after block.

See Also

  • Cache — mutex storage for without_overlapping
  • Artisan-Console — schedule:run, schedule:list
  • Queues — dispatching jobs from scheduled tasks

Clone this wiki locally