# Task Scheduling

- [Introduction](#introduction)
- [Defining schedules](#defining-schedules)
    - [Scheduling commands and programs](#scheduling-commands-and-programs)
    - [Scheduling queued jobs](#scheduling-queued-jobs)
- [Running the scheduler](#running-the-scheduler)
    - [Running the scheduler locally](#running-the-scheduler-locally)
    - [Listing tasks](#listing-tasks)
- [Frequencies and constraints](#frequencies-and-constraints)
    - [Additional constraints](#additional-constraints)
    - [Timezones](#timezones)
- [Preventing overlap](#preventing-overlap)
- [Running on one runner](#running-on-one-runner)
    - [Naming tasks](#naming-tasks)
- [Running tasks in order](#concurrent-tasks)
- [Sub-minute tasks](#sub-minute-tasks)
    - [Interrupting sub-minute tasks](#interrupting-sub-minute-tasks)
- [Task output](#output-and-hooks)
- [Task hooks](#task-hooks)
- [Events](#lifecycle-events)
- [Scheduling from packages](#scheduling-from-packages)
- [Testing](#testing)

<a name="introduction"></a>

## Introduction


週次ダイジェストの送信や毎晩の古いレコードの削除など、多くのアプリケーションには HTTP リクエストへの応答とは別に定期実行する処理があります。従来は処理ごとにサーバーの cron エントリーを管理し、スケジュールがソース管理外に置かれ、変更のたびに SSH で接続する必要があったかもしれません。


Laravel のスケジューラでは、実行するコマンドとともにアプリケーションコードで全スケジュールを Fluent な形式で記述できます。スケジュールはソース管理され、アプリとともにデプロイされます。サーバーには毎分 `schedule:run` を実行する cron エントリーが 1 つあれば十分です。

<a name="defining-schedules"></a>

## Defining schedules


新しいアプリケーションでは、Laravel が自動検出する `#[schedule::tasks]` 属性を使い、`src/console/mod.rs` にスケジュールを定義します。次の例では毎日午前 0 時に非同期関数を呼び出してテーブルを整理します。

```rust
use laravel::db;
use laravel::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.call(prune_recent_users).daily();
}

async fn prune_recent_users() -> laravel::Result<()> {
    db::table("recent_users").delete().await?;

    Ok(())
}
```


スケジュールされたコールバックには、`()` または `laravel::Result<()>` を返す非同期関数やクロージャを使用できます。`Inject<T>` のサービスや `Section<T>` の [config sections](/ja/rust/docs/configuration#your-own-config-sections) も受け取れます。これらは実行ごとに新しい [application context](/ja/rust/docs/context) 内で解決されます。

```rust
use laravel::config::Section;
use laravel::container::Inject;
use laravel::schedule::{self, Schedule};

use crate::config::billing::Billing;
use crate::services::BillingService;

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.call(sync_invoices).hourly();
}

async fn sync_invoices(
    billing: Inject<BillingService>,
    config: Section<Billing>,
) -> laravel::Result<()> {
    billing.sync_due_invoices(&config.account_id).await?;

    Ok(())
}
```


スケジュールの定義自体が設定に依存する場合、`schedule` 関数は 2 番目のパラメータとして `&Config` も受け取れます。

```rust
use laravel::config::Config;
use laravel::schedule::{self, Schedule};

use crate::config::billing::Billing;

#[schedule::tasks]
fn schedule(schedule: &mut Schedule, config: &Config) {
    let billing = config.section::<Billing>();

    if billing.sync_enabled {
        schedule.call(sync_invoices).daily_at(&billing.sync_at);
    }
}
```

<a name="scheduling-commands-and-programs"></a>

### Scheduling commands and programs


コールバックに加え、[console commands](/ja/rust/docs/console#writing-commands) や外部プログラムも予約できます。`command` は新しいプロセスでアプリケーションのコマンドを実行します。ターミナルと同じ形式で記述すると、スケジューラはシェルを起動せず、シェル形式の引用規則で引数を分割するため、`$HOME` のような変数や `*` のような glob は文字どおり渡されます。

```rust
schedule.command("emails:send Taylor --force").daily_at("08:00");
```


設定値など実行時に決まる引数は `args` で追加すると、空白、引用符、`$` をエスケープする必要がありません。外部実行ファイルの予約にも `exec` と `args` を使います。

```rust
use laravel::config::Config;
use laravel::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule, config: &Config) {
    schedule.command("backup:run --disk").args([&config.filesystems.default]).daily();

    schedule.exec("node").args(["scripts/report.js"]).hourly();
}
```


パイプやリダイレクトを含むコマンドをシェル経由で実行するには、`shell` を使います。

```rust
schedule.shell("node scripts/report.js | gzip > storage/report.gz").daily();
```


`shell` には信頼できるコマンド文字列だけを渡し、ユーザー入力は絶対に渡さないでください。すべての予約プロセスはアプリケーションのベースパスを作業ディレクトリとして実行します。

<a name="scheduling-queued-jobs"></a>

### Scheduling queued jobs


コールバックは `schedule:run` プロセス内で動くため、デプロイやクラッシュで長時間の処理が中断される場合があります。数秒以上かかる処理は `job` で [queued job](/ja/rust/docs/queues) を予約し、キューワーカーでバックグラウンド処理します。

```rust
use laravel::schedule::{self, Schedule, Weekday};

use crate::jobs::SendWeeklyDigest;

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule
        .job(SendWeeklyDigest)
        .weekly_on(Weekday::Monday, "08:00");
}
```


ジョブの既定のキューや接続を上書きするには、`on_queue` と `on_connection` を使います。

```rust
schedule
    .job(SendWeeklyDigest)
    .on_connection("redis")
    .on_queue("emails")
    .weekly_on(Weekday::Monday, "08:00");
```

<a name="running-the-scheduler"></a>

## Running the scheduler


`schedule:run` コマンドはスケジュールを評価し、現在の分に実行予定のタスクをすべて実行します。サーバーにはコンパイル済みバイナリを毎分呼び出す cron エントリーを 1 つ追加します。

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


実行予定のタスクは並行実行され、`schedule:run` はすべての完了を待って終了します。タスクが失敗すると Laravel は [error handler](/ja/rust/docs/errors#reporting-errors) に報告し、残りの実行を続けます。停止中に実行できなかった分は後から補いません。

> [!NOTE]
> [Laravel Cloud](https://laravel.com/cloud) へのデプロイでは、cron エントリーを手動設定せずに Cloud がアプリケーションのスケジューラを自動管理・実行できます。

<a name="running-the-scheduler-locally"></a>

### Running the scheduler locally


ローカル開発では cron の設定は不要です。`schedule:work` を実行すると、停止するまで毎分の開始時に `schedule:run` を呼び出します。

```shell
laravel schedule:work
```

<a name="listing-tasks"></a>

### Listing tasks


`schedule:list` で、すべての予約タスクの cron 式と UTC での次回実行時刻を確認できます。完全なコマンド行を表示するには `-v`、機械可読の出力には `--json` を渡します。

```shell
laravel schedule:list
```

<a name="frequencies-and-constraints"></a>

## Frequencies and constraints


既定ではタスクは毎分実行され、すべての頻度は UTC で評価されます。以下の頻度メソッドでスケジュールを調整できます。

| メソッド | スケジュール |
| --- | --- |
| `cron("*/5 8-17 * * MON-FRI")` | 5 フィールドの独自 cron 式 |
| `every_second()`、`every_five_seconds()`、`every_thirty_seconds()` など | [sub-minute tasks](#sub-minute-tasks) の説明どおり、1 分内に複数回 |
| `every_minute()` | 毎分 |
| `every_two_minutes()`、`every_five_minutes()`、`every_fifteen_minutes()` など | 数分ごと |
| `hourly()`、`hourly_at(17)` | 毎時 0 分または指定した分 |
| `every_two_hours()`、`every_six_hours()` など | 午前 0 時を起点に数時間ごと |
| `daily()`、`daily_at("13:00")` | 毎日午前 0 時または指定時刻 |
| `twice_daily(1, 13)`、`twice_daily_at(1, 13, 15)` | 毎日指定した 2 つの時の 0 分または指定した分 |
| `weekly()`、`weekly_on(Weekday::Monday, "08:00")` | 日曜午前 0 時または指定した曜日と時刻 |
| `monthly()`、`monthly_on(4, "15:00")` | 毎月 1 日午前 0 時または指定した日と時刻 |
| `days_of_month([1, 10, 20])` | 毎月指定した日の午前 0 時 |
| `twice_monthly(1, 16, "13:00")` | 毎月 2 つの日の指定時刻 |
| `last_day_of_month("15:00")` | 毎月末日の指定時刻 |
| `quarterly()`、`quarterly_on(4, "14:00")` | 1 月、4 月、7 月、10 月の 1 日午前 0 時、またはその月の指定した日と時刻 |
| `yearly()`、`yearly_on(6, 1, "17:00")` | 1 月 1 日午前 0 時、または指定した月、日、時刻 |


`weekdays`、`weekends`、または `mondays` から `sundays` のメソッドで曜日を絞れます。`days([Weekday::Sunday, Weekday::Wednesday])` は特定の曜日を選び、`at("13:00")` は時刻を設定します。次のタスクは毎週月曜の 13:00 に実行されます。

```rust
schedule.command("reports:generate").weekly().mondays().at("13:00");
```

<a name="additional-constraints"></a>

### Additional constraints


指定時間帯だけ実行するには `between`、その時間帯を除外するには `unless_between` を使います。両端の時刻を含み、`23:00` から `04:00` のように午前 0 時をまたぐ時間帯も指定できます。

```rust
schedule.command("emails:send").hourly().between("08:00", "17:00");
```


`environments` で、`APP_ENV` と一致する特定の [environments](/ja/rust/docs/configuration#determining-the-current-environment) だけにタスクを制限できます。

```rust
schedule.command("emails:send")
    .daily()
    .environments(["staging", "production"]);
```


非同期述語が `true` を返すときだけ実行するには `when`、`true` のとき実行を抑止するには `skip` を使います。述語は `bool` または `laravel::Result<bool>` を返し、`Inject<T>` のサービスや `Section<T>` の設定セクションを受け取れます。複数の `when` を付けた場合はすべてが `true` を返す必要があります。

```rust
schedule
    .command("emails:send")
    .daily()
    .skip(async || {
        let today = laravel::now();

        today.month() == 12 && today.day() == 25
    });
```

<a name="timezones"></a>

### Timezones


スケジューラはすべての時刻を UTC で評価します。年間を通してシカゴの午前 8 時にレポートを送るなど、夏時間の切り替えにも現地時刻を維持する場合は、候補となる 2 つの UTC 時刻を予約し、`when` 述語で現地時刻を確認します。

```rust
schedule
    .command("reports:send")
    .twice_daily(13, 14)
    .when(async || -> laravel::Result<bool> {
        Ok(laravel::now().in_tz("America/Chicago")?.hour() == 8)
    });
```

<a name="preventing-overlap"></a>

## Preventing overlap


既定では前回の実行が続いていても予約タスクは実行されます。前回が進行中なら実行を省略するには、`without_overlapping` を連結します。

```rust
schedule.command("emails:send").every_minute().without_overlapping();
```


`without_overlapping` は所要時間が予測できないタスクに特に便利です。実行中は [cache](/ja/rust/docs/cache) ストアにロックを取得します。`schedule:run` は呼び出しごとに別プロセスで動くため、`database` や `redis` などの共有キャッシュストアを設定してください。既定の `memory` ストアは単一プロセス内に限定され、呼び出し間の調整には使えません。


既定のキャッシュストアが共有されていなければ、`use_cache` で全予約タスク用の共有ストアを選択します。`database` ストアには [lock table](/ja/rust/docs/cache#the-database-store) が必要です。

```rust
#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.use_cache("database");

    schedule.command("emails:send").every_minute().without_overlapping();
}
```


重複防止ロックは 24 時間後に自動失効し、クラッシュしたプロセスがタスクを永続的に妨げるのを防ぎます。短い有効期間にするには、想定される最大実行時間より長い期間で `without_overlapping_for` を呼び出します。

```rust
use laravel::time::ToSpan;

schedule
    .call(prune_recent_users)
    .name("prune-recent-users")
    .every_minute()
    .without_overlapping_for(10.minutes());
```


`without_overlapping` を使うコールバックには、安定したロックキーを生成できるように `name` を指定する必要があります。


クラッシュでロックが残った場合は、`schedule:clear-cache` で重複防止ロックをすべて削除します。実行中タスクのロックも解放するため、クラッシュからの復旧時だけ使用してください。

```shell
laravel schedule:clear-cache
```

<a name="running-on-one-runner"></a>

## Running on one runner


複数サーバーで `schedule:run` を実行すると、調整しない限りすべてのサーバーがすべての予定タスクを実行します。たとえば 3 台で動かすと、金曜夕方のレポートを各サーバーが生成します。その分では 1 台だけが実行するよう `on_one_runner` を連結します。

```rust
schedule.command("reports:generate")
    .fridays()
    .at("17:00")
    .on_one_runner();
```


最初に到達したサーバーがその分のキャッシュロックを取得し、ほかのサーバーは省略します。[preventing overlap](#preventing-overlap) の説明どおり、全サーバーで同じキャッシュストアを共有する必要があります。


`on_one_runner` が重複を除くのは同じ 1 分内だけなので、1 分を超える可能性のあるタスクでは `without_overlapping` と併用してください。

<a name="naming-tasks"></a>

### Naming tasks


サーバーは名前、スケジュール、コマンドでタスクを識別します。Rust 関数の型名はビルド間で変わり得るため、`on_one_runner` のコールバックには明示的な `name` が必要です。同じコールバックを異なる引数で複数予約する場合は、登録ごとに固有名を付けてください。

```rust
for account in [42, 84] {
    schedule
        .call(move || async move { tracing::info!(account, "Checking account") })
        .name(format!("check-account-{account}"))
        .hourly()
        .on_one_runner();
}
```

<a name="concurrent-tasks"></a>

## Running tasks in order


予定タスクは定義順に開始して並行実行するため、完了順は一定しません。後続タスクが先行タスクの完了を待つ必要がある場合は、先行タスクに `blocking` を付けます。

```rust
schedule.command("reports:generate").hourly();
schedule.command("accounts:reconcile").hourly().blocking();
schedule.command("statements:send").hourly();
```


ここでは `statements:send` は `accounts:reconcile` の終了を待ちますが、`accounts:reconcile` は `reports:generate` と並行実行されます。複数のステップを常に厳密な順序で実行する必要があるなら、1 つのコールバックやコマンドにまとめてください。

<a name="sub-minute-tasks"></a>

## Sub-minute tasks


cron が `schedule:run` を起動するのは毎分 1 回でも、タスクは毎秒の頻度で予約できます。

```rust
schedule.command("orders:sync").every_second();
```


1 分未満のタスクが予定されていると、`schedule:run` はその分の残り時間も動作し、予定どおり繰り返します。追加条件は分単位で適用されるため、`every_ten_seconds().weekdays()` は平日のみ動きます。次の間隔になっても前回が実行中なら、その回を省略します。重い処理は [dispatching queued jobs](#scheduling-queued-jobs) でキューに送り、短周期タスクを軽く保ち、複数サーバーでは [`on_one_runner`](#running-on-one-runner) と併用してください。


メモリ内バッファのフラッシュなど、各サーバープロセスやキューワーカー内の定期処理には [tick](/ja/rust/docs/tasks#ticks) を使います。tick は `serve` と `queue:work` 内で実行され、cron は不要です。

<a name="interrupting-sub-minute-tasks"></a>

### Interrupting sub-minute tasks


1 分未満のタスクがあると `schedule:run` はその分の終わりまで動くため、デプロイ前に開始した実行は前のビルドで繰り返し続けます。早く停止するには、新しいビルドの配置後に、デプロイスクリプトで `schedule:interrupt` を実行します。

```shell
./your-app schedule:interrupt
```


全サーバーの実行中の各 `schedule:run` は、1 秒以内にシグナルを認識します。繰り返しの追加を止め、実行中タスクの完了を待って終了します。次の分の `schedule:run` は新ビルドを使います。シグナルは [overlap locks](#preventing-overlap) と同じキャッシュストアを経由するため、`memory` ではなく `database` や `redis` のように全プロセスで共有するストアが必要です。

<a name="output-and-hooks"></a>

## Task output


既定では、スケジューラは予約コマンドと外部プロセスのコンソール出力を破棄します。ファイルに保存するには、先に保存先ディレクトリを用意し、`send_output_to` で上書き、`append_output_to` で追記します。

```rust
schedule
    .command("emails:send")
    .daily()
    .send_output_to("storage/logs/emails.log");

schedule
    .command("emails:send")
    .daily()
    .append_output_to("storage/logs/emails.log");
```


予約コマンドのログと報告されたエラーは、`send_output_to` がなくても設定済みの [log channels](/ja/rust/docs/logging#channels) に自動送信されます。予約クロージャには取得対象のプロセス出力がないため、クロージャ内でも [logging](/ja/rust/docs/logging) を使用してください。

<a name="task-hooks"></a>

## Task hooks


予約タスクの前後にコードを動かすには、`before`、`after`、`on_success`、`on_failure` を使います。エラーを返す、パニックする、0 以外の終了コードで終了すると失敗とみなします。`before` フックが失敗した場合はタスク自体を実行しません。実行後のフックは、タスクの `error`、`exit_code`、`duration`、`output` を含む `Event<TaskResult>` を受け取ります。

```rust
use laravel::event::Event;
use laravel::schedule::TaskResult;

schedule
    .command("emails:send")
    .daily()
    .before(async || tracing::info!("Sending emails"))
    .on_success(async |result: Event<TaskResult>| {
        tracing::info!(duration = %result.duration, "Sent emails");
    })
    .on_failure(async |result: Event<TaskResult>| {
        tracing::error!(error = ?result.error, "Couldn't send emails");
    });
```


`send_output_to` または `append_output_to` で出力を取得すると、`result.output` に `TaskOutput` が入ります。`text()` と `bytes()` はファイルをメモリに読み取り、`stream()` は全体をバッファリングせず [file storage](/ja/rust/docs/filesystem) にチャンクを送り、`path()` はパスを [email attachment](/ja/rust/docs/mail#attachments) に直接渡せます。

```rust
use laravel::event::Event;
use laravel::schedule::TaskResult;
use laravel::storage;

schedule
    .command("reports:generate")
    .daily()
    .send_output_to("storage/logs/report.log")
    .on_success(async |result: Event<TaskResult>| -> laravel::Result<()> {
        if let Some(output) = &result.output {
            let stream = output.stream().await?;

            storage::disk("s3")?.write_stream("logs/report.log", stream).await?;
        }

        Ok(())
    });
```


`after` フックでは `result.succeeded()` で正常終了したか確認します。予約コールバックと同様、フックも `Inject<T>` のサービスと `Section<T>` の設定セクションを受け取れます。

<a name="lifecycle-events"></a>

## Events


スケジューラはタスクのライフサイクルを通して `laravel::schedule::events` の [events](/ja/rust/docs/events) を送出します。`ScheduledTaskFailed` を監視すれば、すべての予約タスクの失敗通知を一元化できます。

| イベント | 送出されるタイミング |
| --- | --- |
| `ScheduledTaskStarting` | タスクの開始時。 |
| `ScheduledTaskFinished` | 結果にかかわらずタスクとフックが終了したとき。 |
| `ScheduledTaskSkipped` | `when` や `skip` の述語、別のランナー、重複防止ロックにより予定タスクを省略したとき。 |
| `ScheduledTaskFailed` | タスク、述語、ロック、フックが失敗したとき。 |


タスクの監視や失敗通知には、`src/listeners/` に [listener](/ja/rust/docs/events#defining-listeners) を定義します。

```rust
use laravel::event::{Event, listener};
use laravel::schedule::events::ScheduledTaskFailed;

#[listener]
pub async fn log_failed_task(event: Event<ScheduledTaskFailed>) {
    tracing::error!(
        task = %event.result.task.name,
        error = ?event.result.error,
        "Scheduled task failed",
    );
}
```

<a name="scheduling-from-packages"></a>

## Scheduling from packages


パッケージは [service provider's](/ja/rust/docs/packages#service-providers) `register` メソッド内で、夜間のクリーンアップや朝のレポートなど独自のタスクを予約できます。

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

impl ServiceProvider for ReportsProvider {
    fn register(&self, app: &mut Registrar) {
        app.commands().add::<GenerateReport>();

        app.schedule().command("reports:generate").daily_at("06:00");
    }
}
```


ここで `ReportsProvider` はパッケージのサービスプロバイダ、`GenerateReport` は [command struct](/ja/rust/docs/console#command-structs) です。

<a name="testing"></a>

## Testing


スケジューラは実行時刻を決めるだけなので、テストで動かす必要はありません。各タスクはコマンド、ジョブ、非同期関数のいずれかで、それぞれ直接テストできます。予約されていない場合と同じテストを書いてください。


`schedule` 内のインラインクロージャはテストから呼べないため、`call` に渡す処理を名前付きの `pub async fn` に移し、その名前で予約します。たとえば [Defining schedules](#defining-schedules) の `prune_recent_users` を `src/console/mod.rs` で `pub` にし、`src/lib.rs` に `pub mod console;` を宣言すると、統合テストからインポートできます。

```rust
// src/console/mod.rs
use laravel::db;
use laravel::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.call(prune_recent_users).daily();
}

pub async fn prune_recent_users() -> laravel::Result<()> {
    db::table("recent_users").delete().await?;

    Ok(())
}
```


続いて、テスト用アプリケーションとデータベース内で動く `#[laravel::test]` から関数を直接呼び出します。

```rust
// tests/scheduling.rs
use laravel::db;
use laravel::testing::prelude::*;

#[laravel::test]
async fn pruning_recent_users_empties_the_table(app: Application) -> laravel::Result<()> {
    db::table("recent_users")
        .insert(db::values! { name: "Taylor" })
        .await?;

    app::console::prune_recent_users().await?;

    app.assert_database_count("recent_users", 0).await;

    Ok(())
}
```


予約コマンドは、コンソールガイドの [testing commands](/ja/rust/docs/console#testing-commands) のとおり `app.command` で実行します。予約ジョブは、キューガイドの [testing a job](/ja/rust/docs/queues#testing-a-job) のとおり `app.job` で 1 回の試行を実行します。

```rust
app.command("emails:send Taylor --force").await.assert_successful();

app.job(SendWeeklyDigest).await.assert_succeeded();
```


前月のレポートなど処理が日付に依存する場合は、関数、コマンド、ジョブを呼ぶ前にその日付へ [travel](/ja/rust/docs/testing#time-travel) してください。実行時刻は、全タスクの次回実行時刻を表示する [`schedule:list`](#listing-tasks) で確認できます。