跳至正文

Task Scheduling ​

Introduction ​

Some work in your application happens on a clock instead of in response to a request, such as sending a weekly digest or deleting stale records every night. In the past, you may have written a cron entry on your server for each of these tasks. That keeps your schedule on the server instead of in source control, and you have to log in to the server whenever you want to see or change it.

Laravel's scheduler lets you define your schedule in your application's code, next to the commands it runs. The schedule goes through code review and deploys with the rest of your application, and your server needs only one cron entry, which runs the scheduler every minute.

Defining schedules ​

New applications define their schedule in the Schedule function in commands/schedule.go, which bootstrap/app.go passes to the application as Options.Schedule. For example, this schedule calls a function every day at midnight to clear a table:

go
package commands

import (
	"context"

	"go.laravel.com/db"
	"go.laravel.com/schedule"
)

func Schedule(ctx context.Context, s *schedule.Schedule) {
	s.Call("prune-recent-users", func(ctx context.Context) error {
		_, err := db.Table("recent_users").Delete(ctx)

		return err
	}).Daily()
}

Call takes a name for the task and the function to run. The name identifies the task in schedule:list, in the log, and in the scheduler's locks. If the function returns an error or panics, the task fails.

Each time the task runs, its function receives a ctx of its own, which carries your application. Pass that ctx to reach the database, the queue, and your application's services with services.From(ctx). For example, this task syncs the invoices that are due with your billing provider every hour:

go
func Schedule(ctx context.Context, s *schedule.Schedule) {
	s.Call("sync-invoices", func(ctx context.Context) error {
		return services.From(ctx).Billing.SyncDueInvoices(ctx)
	}).Hourly()
}

Here, Billing stands for a billing client of your own, which services.New builds in services/services.go.

The Schedule function receives a context too, so the schedule itself may depend on your settings. For example, you might sync invoices only when billing is turned on, at the time your billing settings name:

go
func Schedule(ctx context.Context, s *schedule.Schedule) {
	billing := services.From(ctx).Billing

	if billing.SyncEnabled {
		s.Call("sync-invoices", billing.SyncDueInvoices).DailyAt(billing.SyncAt)
	}
}

Laravel's own settings are there as well, through config.From(ctx).

Scheduling commands and programs ​

In addition to functions, you may schedule your own console commands and other programs. Command runs one of your commands in a new process of your application. Write the command line as you'd type it after laravel. The scheduler splits the line into words the way a shell does, but it doesn't start a shell, so $HOME and * reach the command exactly as written:

go
s.Command("emails:send Taylor --force").DailyAt("08:00")

When your code computes an argument, such as a value from configuration, pass the value after the command line instead. The scheduler adds each of those arguments exactly as given, so spaces, quotes, and $ need no escaping. To run another program, use Exec, which takes the program's name followed by its arguments:

go
s.Command("backup:run --disk", config.From(ctx).Filesystems.Default).Daily()
s.Exec("node", "scripts/report.js").Hourly()

If a command line needs a shell's pipes or redirects, use Shell:

go
s.Shell("node scripts/report.js | gzip > storage/report.gz").Daily()

Pass Shell only command lines you wrote, never user input. Every process runs in your application's base directory, so relative paths start there.

Scheduling queued jobs ​

A scheduled function runs inside the schedule:run process, so a deploy or a crash can stop the function partway through. For work that takes more than a few seconds, schedule a queued job with Job. When the task is due, the scheduler pushes the job onto your queue, and a worker runs it:

go
s.Job(jobs.SendWeeklyDigest{}).WeeklyOn(time.Monday, "08:00")

Use OnQueue and OnConnection to override the job's default queue or queue connection:

go
s.Job(jobs.SendWeeklyDigest{}).
	OnConnection("redis").
	OnQueue("emails").
	WeeklyOn(time.Monday, "08:00")

List the job's type in jobs.All, as you would for any job you dispatch.

Running the scheduler ​

The schedule:run command starts every task that's due in the current minute. On your server, add one cron entry that runs it every minute, using your built binary:

cron
* * * * * cd /path/to/your-app && ./app schedule:run >> /dev/null 2>&1

Due tasks run at the same time, and schedule:run waits for all of them to finish before it exits. If a task fails, the scheduler logs the error, still runs the other tasks, and then exits with status 1. The scheduler doesn't catch up on minutes it missed, such as while the server was down.

说明

On Laravel Cloud, Cloud runs the scheduler for your application, so you don't need a cron entry.

Running the scheduler locally ​

You usually won't add a cron entry on your local machine. Instead, run schedule:work, which runs the due tasks at the start of every minute and shows their output until you stop it:

shell
laravel schedule:work

Listing tasks ​

To see every task with its schedule and next run time in UTC, run schedule:list. Add -v to include each task's full command line, or --json for output that other tools can read:

shell
laravel schedule:list

Frequencies and constraints ​

The scheduler evaluates cron expressions, days of the week, and time windows in UTC. A task runs every minute unless you give it another frequency. You may choose any of these frequency methods:

MethodSchedule
Cron("*/5 8-17 * * MON-FRI")A custom five-field cron expression
EverySecond(), EveryFiveSeconds(), EveryThirtySeconds(), and othersSeveral times within each minute, as sub-minute tasks describes
EveryMinute()Every minute
EveryTwoMinutes(), EveryFiveMinutes(), EveryFifteenMinutes(), and othersEvery few minutes
Hourly(), HourlyAt(17)Every hour, at minute zero or the given minute
EveryTwoHours(), EverySixHours(), and othersEvery few hours, counting from midnight
Daily(), DailyAt("13:00")Every day, at midnight or the given time
TwiceDaily(1, 13), TwiceDailyAt(1, 13, 15)Every day at the two given hours, at minute zero or the given minute
Weekly(), WeeklyOn(time.Monday, "08:00")Sunday at midnight, or the given weekday and time
Monthly(), MonthlyOn(4, "15:00")The first day at midnight, or the given day and time
DaysOfMonth(1, 10, 20)The given days of the month, at midnight
TwiceMonthly(1, 16, "13:00")Two days of the month, at the given time
LastDayOfMonth("15:00")The month's last day, at the given time
Quarterly(), QuarterlyOn(4, "14:00")The first day of January, April, July, and October at midnight, or the given day and time of those months
Yearly(), YearlyOn(time.June, 1, "17:00")January 1st at midnight, or the given month, day, and time

You may narrow a frequency to certain days of the week with Weekdays, Weekends, or Mondays through Sundays. Days(time.Sunday, time.Wednesday) picks the days you name, and At("13:00") sets the time of day. This task runs every Monday at 13:00:

go
s.Command("reports:generate").Weekly().Mondays().At("13:00")

Additional constraints ​

Sometimes a task should run only at certain times, such as sending emails during business hours. Between runs a task only within a window of time, and UnlessBetween skips the task within one. Both methods include the end times, and the window may cross midnight, such as 23:00 to 04:00:

go
s.Command("emails:send").Hourly().Between("08:00", "17:00")

Environments runs a task only in the given environments, as APP_ENV sets them:

go
s.Command("emails:send").Daily().Environments("staging", "production")

When runs a task only when a function of yours returns true, and Skip skips the task when its function returns true. If you add several When functions, the task runs only when every one of them returns true. A function that returns an error fails the task. For example, this task skips Christmas Day:

go
s.Command("emails:send").Daily().Skip(func(ctx context.Context) (bool, error) {
	_, month, day := date.Now(ctx).UTC().Date()

	return month == time.December && day == 25, nil
})

Timezones ​

The scheduler evaluates all times in UTC. If a task must follow a local timezone across daylight saving transitions, such as sending a report at 8:00 AM Chicago time all year, schedule both candidate UTC hours and check the local hour in a When predicate:

go
chicago, _ := time.LoadLocation("America/Chicago")

s.Command("reports:send").TwiceDaily(13, 14).When(func(ctx context.Context) (bool, error) {
	return date.Now(ctx).In(chicago).Hour() == 8, nil
})

Preventing overlap ​

By default, a task starts even if its previous run is still going. To skip a run while an earlier one is still in progress, use WithoutOverlapping:

go
s.Command("emails:send").EveryMinute().WithoutOverlapping()

WithoutOverlapping holds a lock in your cache while the task runs. Each schedule:run is its own process, so the lock needs a store that every process shares, such as the database store with its lock table. The memory store keeps the lock inside one process, where the next minute's schedule:run can't see it. If you use a lock with the memory store, schedule:list warns you.

If your default cache store isn't one that every process shares, you may keep the scheduler's locks in another store with UseCache. Pass it a store from cache.Named, and every task's locks go there:

go
func Schedule(ctx context.Context, s *schedule.Schedule) {
	s.UseCache(cache.Named(ctx, "database"))

	s.Command("emails:send").EveryMinute().WithoutOverlapping()
}

The lock expires after 24 hours, in case a crash leaves it behind. To choose a shorter time, use WithoutOverlappingFor with a length longer than the task's longest run:

go
s.Call("prune-recent-users", pruneRecentUsers).EveryMinute().WithoutOverlappingFor(10 * time.Minute)

If a crash leaves a task's lock behind, the schedule:clear-cache command releases the overlap locks of every task. Run it only to recover from a crash, because it also releases the locks of tasks that are still running:

shell
laravel schedule:clear-cache

Running on one runner ​

When schedule:run runs on several servers, every server runs every task. For example, if three servers run the scheduler, your Friday evening report is generated three times. OnOneRunner lets only one server run the task each minute:

go
s.Command("reports:generate").Fridays().At("17:00").OnOneRunner()

The first server to reach the task takes a lock in your cache for that minute, and the other servers skip the task. Every server must share the same cache store, so set the store up as preventing overlap describes.

OnOneRunner doesn't stop a long task from overlapping the next minute's run, so combine it with WithoutOverlapping when a run may last longer than a minute.

Naming tasks ​

Servers recognize a task by its name, its schedule, and the command it runs. A job's task is named after the job's type, so if you schedule one job type several times with different values, give each task its own name with Name. Otherwise, the servers can't tell the tasks apart, and only one of them runs:

go
s.Job(jobs.SendDigest{Plan: "pro"}).Name("pro-digest").Daily().OnOneRunner()
s.Job(jobs.SendDigest{Plan: "free"}).Name("free-digest").Daily().OnOneRunner()

Running tasks in order ​

Due tasks start in the order you defined them, but they run at the same time, so they may finish in any order. Sometimes a later task needs an earlier one's results, such as sending statements only after the accounts are reconciled. Mark the earlier task Blocking, and the tasks defined after it wait for it to finish:

go
s.Command("reports:generate").Hourly()
s.Command("accounts:reconcile").Hourly().Blocking()
s.Command("statements:send").Hourly()

Here, statements:send waits for accounts:reconcile to finish, but accounts:reconcile doesn't wait for reports:generate, which started before it. If several steps must always run together, put them in one function or command.

Sub-minute tasks ​

Cron starts schedule:run at most once a minute, but a scheduled task may run as often as every second:

go
s.Command("orders:sync").EveryTenSeconds()

When a sub-minute task is due, schedule:run keeps running for the rest of the minute and repeats the task within it. The other frequency methods still pick the minutes, so EveryTenSeconds().Weekdays() repeats only on weekdays. If a repeat comes due while the previous run is still going, the scheduler skips that repeat. Keep sub-minute tasks short by scheduling a queued job for longer work, and use OnOneRunner when several servers run the scheduler.

For work that repeats inside each server process, such as flushing counts buffered in memory, use a tick instead. Ticks run inside serve and need no cron entry.

Interrupting sub-minute tasks ​

Because schedule:run keeps running for the rest of the minute when a sub-minute task is due, a run that started before you deployed keeps repeating its tasks with your previous build until the minute ends. To stop it sooner, add the schedule:interrupt command to your deployment script, after the new binary is in place:

shell
./app schedule:interrupt

Each schedule:run in progress, on every server, notices the signal within a second. It starts no more repeats, waits for the tasks already running to finish, and exits. The next minute's schedule:run uses your new binary. The signal travels through the same cache store as the scheduler's overlap locks, so that store must be one every process shares, such as database or redis, rather than memory.

Task output ​

The scheduler discards what a command, program, or shell command prints. To keep the output, use SendOutputTo, which replaces a file's contents with the output, or AppendOutputTo, which adds the output to the end of a file. A relative path starts at your application's base directory, and the file's directory must already exist:

go
s.Command("emails:send").Daily().SendOutputTo("storage/logs/emails.log")

s.Command("emails:send").Daily().AppendOutputTo("storage/logs/emails.log")

A function or a job has no output to capture, so write log entries from it instead.

Task hooks ​

Sometimes you need to know how a task went, such as alerting someone when a nightly import fails. You may run code before a task with Before, and after the task with After, OnSuccess, and OnFailure. A task fails when it returns an error, panics, or exits with a status other than 0. If a Before hook fails, the task doesn't run. The other hooks receive a schedule.Result, which holds the task's Err, ExitCode, Duration, and the path of its Output file:

go
s.Command("emails:send").Daily().
	Before(func(ctx context.Context) error {
		slog.InfoContext(ctx, "Sending the emails.")

		return nil
	}).
	OnSuccess(func(ctx context.Context, result schedule.Result) error {
		slog.InfoContext(ctx, "Sent the emails.", "duration", result.Duration)

		return nil
	}).
	OnFailure(func(ctx context.Context, result schedule.Result) error {
		slog.ErrorContext(ctx, "Couldn't send the emails.", "error", result.Err)

		return nil
	})

When a task sends its output to a file with SendOutputTo or AppendOutputTo, result.Output holds the file's path, joined to your application's base directory, so a hook may read the file. For example, this hook copies a report's output to file storage, streaming the file rather than reading it into memory:

go
s.Command("reports:generate").Daily().
	SendOutputTo("storage/logs/report.log").
	OnSuccess(func(ctx context.Context, result schedule.Result) error {
		output, err := os.Open(result.Output)
		if err != nil {
			return err
		}
		defer output.Close()

		return storage.Use("s3").WriteStream(ctx, "logs/report.log", output)
	})

To attach the output to an email instead, pass the path to mail.AttachFile.

Inside an After hook, which runs whether or not the task succeeded, call result.Succeeded() to check whether the task finished cleanly. Like a scheduled function, each hook receives a ctx that carries your application, so it may reach your services with services.From(ctx).

Events ​

Hooks handle one task at a time. To handle every task's failures in one place, such as reporting them all to your team's chat, listen for the events that the scheduler dispatches from the schedule package as tasks run:

EventDispatched when
TaskStartingA task starts.
TaskFinishedA task and its hooks finish, whether or not the task succeeded.
TaskSkippedA due task doesn't run because of a When or Skip function, another runner, or an overlap lock.
TaskFailedA task, check, lock, or hook fails.

Define a listener in your listeners package to alert you when any task fails:

go
func ReportFailedTask(ctx context.Context, e schedule.TaskFailed) error {
	slog.ErrorContext(ctx, "A scheduled task failed.", "task", e.Result.Task.Name, "error", e.Result.Err)

	return nil
}

To register the listener, add laravel.Listen(ReportFailedTask) to listeners.All. To learn more about listeners, check out the events guide.

While a task runs, Laravel adds the task's name to every line you log with the task's ctx, as a task field, so you may find a task's lines in your logs without logging its name yourself:

text
level=INFO msg="Sent the emails." duration=1.204s task=emails:send

To learn more about the fields Laravel adds to log lines, check out the logging guide's section on commands, jobs, and scheduled tasks.

Scheduling from packages ​

A package may ship tasks of its own, such as a report it generates every morning. The package schedules them from its Register method with app.Schedule, and Laravel defines them before the application's own schedule:

go
func (Package) Register(app *laravel.Registrar) error {
	app.Commands(&GenerateReport{})
	app.Schedule(func(ctx context.Context, s *schedule.Schedule) {
		s.Command("reports:generate").DailyAt("06:00")
	})

	return nil
}

Here, GenerateReport is the package's command. To learn more about writing packages, check out the package guide.

Testing ​

The scheduler only decides when your tasks run, so your tests don't need to run it. Each task is a command, a job, or a function, and you may test each of those directly with the test client. For each one, write the test you'd write if nothing scheduled it.

A function written inline in Schedule can't be called from a test, so give the function you pass to Call a name of its own, and schedule it by that name. For example, the nightly cleanup from Defining schedules might move into a PruneRecentUsers function in commands/schedule.go:

go
package commands

import (
	"context"

	"go.laravel.com/db"
	"go.laravel.com/schedule"
)

func Schedule(ctx context.Context, s *schedule.Schedule) {
	s.Call("prune-recent-users", PruneRecentUsers).Daily()
}

func PruneRecentUsers(ctx context.Context) error {
	_, err := db.Table("recent_users").Delete(ctx)

	return err
}

Your test then calls the function with the test client's context, which carries the test's application and database:

go
package feature_test

import (
	"testing"

	"go.laravel.com/db"

	"app/commands"
	"app/tests"
)

func TestPruningRecentUsersEmptiesTheTable(t *testing.T) {
	client := tests.New(t)

	err := db.Table("recent_users").Insert(client.Context(), db.Values{"name": "Taylor"})
	if err != nil {
		t.Fatal(err)
	}

	if err := commands.PruneRecentUsers(client.Context()); err != nil {
		t.Fatal(err)
	}

	client.AssertDatabaseCount("recent_users", 0)
}

To test a scheduled command, run its command line with client.Command, as the console guide's section on testing commands shows. To test a scheduled job, run one attempt of it with client.Attempt, as the queue guide's section on testing a job shows:

go
client.Command("emails:send Taylor --force").AssertSuccessful()
client.Attempt(jobs.SendWeeklyDigest{}).AssertSucceeded()

If your task's work depends on the date, such as a report that covers the previous month, travel to that date before you call the function, command, or job. To check when each task runs, run schedule:list, which shows every task's next run time.