# 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 스케줄러로 실행할 명령어와 함께 애플리케이션 코드에서 전체 일정을 플루언트 방식으로 표현할 수 있습니다. 일정은 소스 관리에 포함되어 앱과 함께 배포되며, 서버에는 매분 `schedule:run`을 실행하는 cron 항목 하나만 있으면 됩니다.

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

## Defining schedules


새 애플리케이션은 Laravel이 자동으로 발견하는 `#[schedule::tasks]` 속성으로 `src/console/mod.rs`에 일정을 정의합니다. 다음 일정은 매일 자정에 비동기 함수를 호출하여 테이블을 정리합니다.

```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](/rust/docs/configuration#your-own-config-sections)를 받을 수도 있으며, 실행할 때마다 새로운 [application context](/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` 함수의 두 번째 파라미터로 `&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](/rust/docs/console#writing-commands)와 외부 프로그램을 예약할 수 있습니다. `command`는 새 프로세스에서 애플리케이션 명령어를 실행합니다. 터미널처럼 명령줄을 작성하면 스케줄러가 셸을 실행하지 않고 셸 방식의 인용 규칙으로 인수를 분리하므로 `$HOME` 같은 변수와 `*` 같은 글로브는 문자 그대로 전달됩니다.

```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](/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 항목 하나를 추가합니다.

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


실행 시점이 된 작업은 동시에 실행되며 `schedule:run`은 모두 끝날 때까지 기다린 뒤 종료합니다. 작업이 실패하면 Laravel은 [error handler](/rust/docs/errors#reporting-errors)에 오류를 보고하고 나머지 작업을 계속 실행합니다. 중단된 동안 놓친 실행 시간은 나중에 보충하지 않습니다.

> [!NOTE]
> [Laravel Cloud](https://laravel.com/cloud)에 배포하면 Cloud가 수동 cron 항목 없이도 애플리케이션의 스케줄러를 자동으로 관리하고 실행할 수 있습니다.

<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()` 등 | 자정을 기준으로 몇 시간마다 |
| `daily()`, `daily_at("13:00")` | 매일 자정 또는 지정한 시각 |
| `twice_daily(1, 13)`, `twice_daily_at(1, 13, 15)` | 매일 지정한 두 시간의 0분 또는 지정한 분 |
| `weekly()`, `weekly_on(Weekday::Monday, "08:00")` | 일요일 자정 또는 지정한 요일과 시각 |
| `monthly()`, `monthly_on(4, "15:00")` | 매월 1일 자정 또는 지정한 날짜와 시각 |
| `days_of_month([1, 10, 20])` | 매월 지정한 날짜의 자정 |
| `twice_monthly(1, 16, "13:00")` | 매월 두 날짜의 지정한 시각 |
| `last_day_of_month("15:00")` | 매월 마지막 날의 지정한 시각 |
| `quarterly()`, `quarterly_on(4, "14:00")` | 1월, 4월, 7월, 10월의 1일 자정 또는 해당 월의 지정한 날짜와 시각 |
| `yearly()`, `yearly_on(6, 1, "17:00")` | 1월 1일 자정 또는 지정한 월, 일, 시각 |


`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`처럼 자정을 넘는 구간도 가능합니다.

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


`environments`로 `APP_ENV`와 일치하는 특정 [environments](/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시에 보고서를 보내는 것처럼 일광 절약 시간 변경에도 현지 시간대를 따라야 한다면, 후보 UTC 시간 2개를 모두 예약한 뒤 `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](/rust/docs/cache) 저장소에서 잠금을 획득합니다. 각 `schedule:run`은 별도 프로세스이므로 `database`나 `redis` 같은 공유 캐시 저장소를 설정하세요. 기본 `memory` 저장소는 단일 프로세스에 한정되어 호출 사이를 조정할 수 없습니다.


기본 캐시 저장소가 공유되지 않는다면 `use_cache`로 모든 예약 작업에 사용할 공유 저장소를 선택합니다. `database` 저장소에는 [lock table](/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대가 각각 금요일 저녁 보고서를 만들게 됩니다. 해당 분에 서버 하나만 실행하도록 `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`와 동시에 실행됩니다. 여러 단계를 항상 엄격한 순서로 실행해야 한다면 하나의 콜백이나 명령어로 합치세요.

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

## Sub-minute tasks


cron은 `schedule:run`을 매분 한 번 실행하지만, 작업은 매초까지 빈번하게 예약할 수 있습니다.

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


1분 미만 주기의 작업이 예정되면 `schedule:run`은 그 분이 끝날 때까지 활성 상태로 일정을 반복 실행합니다. 추가 제약은 여전히 분 단위로 적용되므로 `every_ten_seconds().weekdays()`는 평일에만 실행됩니다. 다음 간격이 왔을 때 이전 실행이 진행 중이면 해당 실행 시점을 건너뜁니다. 무거운 처리는 [dispatching queued jobs](#scheduling-queued-jobs)로 큐에 보내 1분 미만 주기 작업을 가볍게 유지하고, 여러 서버에서는 [`on_one_runner`](#running-on-one-runner)와 함께 사용하세요.


메모리 버퍼 비우기처럼 각 서버 프로세스나 큐 워커 범위에서 반복하는 작업은 [tick](/rust/docs/tasks#ticks)을 사용합니다. 틱은 `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](/rust/docs/logging#channels)로 자동 전송됩니다. 예약 클로저에는 캡처할 프로세스 출력이 없으므로 클로저 안에서도 [logging](/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](/rust/docs/filesystem)로 청크를 스트리밍하며, `path()`는 경로를 [email attachment](/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](/rust/docs/events)를 디스패치합니다. `ScheduledTaskFailed`를 구독하면 모든 예약 작업 실패의 알림을 한곳에서 관리할 수 있습니다.

| 이벤트 | 디스패치 시점 |
| --- | --- |
| `ScheduledTaskStarting` | 작업이 시작할 때 |
| `ScheduledTaskFinished` | 결과와 관계없이 작업과 훅이 끝날 때 |
| `ScheduledTaskSkipped` | `when`이나 `skip` 조건식, 다른 실행기, 중복 방지 잠금으로 예정된 작업을 건너뛸 때 |
| `ScheduledTaskFailed` | 작업, 조건식, 잠금 또는 훅이 실패할 때 |


작업 실행을 모니터링하거나 실패를 알리려면 `src/listeners/`에 [listener](/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](/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](/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](/rust/docs/console#testing-commands)처럼 `app.command`로 명령줄을 실행합니다. 예약 잡은 큐 가이드의 [testing a job](/rust/docs/queues#testing-a-job)처럼 `app.job`으로 한 번의 시도를 실행합니다.

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

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


이전 달을 대상으로 하는 보고서처럼 처리 내용이 날짜에 의존하면 함수, 명령어 또는 잡을 호출하기 전에 해당 날짜로 [travel](/rust/docs/testing#time-travel)합니다. 각 작업의 실행 시점은 다음 실행 시각을 모두 보여주는 [`schedule:list`](#listing-tasks)로 확인합니다.