메인 콘텐츠로 건너뛰기

InteractsWithTime란

Illuminate\Support\InteractsWithTime은, 시간·지연·경과 시간의 계산을 모은 트레이트입니다. Laravel 프레임워크 내에서는 40개 이상의 클래스가 use InteractsWithTime;을 사용하고 있으며, 캐시·큐·콘솔·데이터베이스 커넥션 등 폭넓은 컴포넌트에서 사용되고 있습니다.
소스 코드는 src/Illuminate/Support/InteractsWithTime.php에 있습니다. protected 메서드만으로 구성되어 있으며, 클래스 내부에서 호출하는 용도를 전제로 합니다.

프레임워크 내의 사용 예

클래스이용 목적
Cache\ArrayStore / DatabaseStoreTTL(유효 기한)의 계산
Cache\RateLimiter레이트 리밋의 리셋 시각
Queue\Console\RestartCommand워커 재시작 타임스탬프
Database\Connection쿼리 실행 시간의 측정
Console\View\Components\Task커맨드 태스크의 실행 시간 표시
Redis\Limiters\DurationLimiterBuilderRedis 레이트 리밋의 기간 계산

메서드 해설

secondsUntil() — 남은 초 수 취득

지정한 일시·지연값까지의 남은 초 수를 반환합니다. 인수에는 DateTimeInterface·DateInterval·초 수의 정수값 중 하나를 전달할 수 있습니다.
use Illuminate\Support\InteractsWithTime;

class MyService
{
    use InteractsWithTime;

    public function scheduleAt(\DateTime $target): int
    {
        return $this->secondsUntil($target); // 現在から $target までの秒数
    }
}
과거의 일시를 전달하면 0을 반환합니다(음수가 되지 않습니다).
$seconds = $this->secondsUntil(now()->addMinutes(5)); // 300
$seconds = $this->secondsUntil(now()->subMinutes(5)); // 0(過去は 0)
$seconds = $this->secondsUntil(60);                   // 60(整数はそのまま秒数)

availableAt() — 이용 가능해지는 UNIX 타임스탬프

현재 시각에 지연을 가산한 UNIX 타임스탬프를 반환합니다. 큐의 잡 지연이나 캐시의 유효 기한 계산에 사용됩니다.
$timestamp = $this->availableAt(60);              // 60 秒後の UNIX タイムスタンプ
$timestamp = $this->availableAt(new \DateTime('2026-12-31')); // 指定日時の UNIX タイムスタンプ
$timestamp = $this->availableAt(new \DateInterval('PT5M'));    // 5 分後
인수 없이(기본값 0)로 호출하면 현재 시각의 타임스탬프를 반환합니다.

parseDateInterval() — DateInterval을 DateTime으로 변환

DateInterval 인스턴스를 받으면, 현재 시각에 가산한 Carbon 인스턴스로 변환하여 반환합니다. DateTimeInterface나 정수값은 그대로 반환합니다.
$delay = $this->parseDateInterval(new \DateInterval('P1D')); // 明日の Carbon
$delay = $this->parseDateInterval(now()->addHour());         // DateTimeInterface はそのまま
$delay = $this->parseDateInterval(3600);                     // 3600(整数はそのまま)
secondsUntil()availableAt()은 내부에서 이 메서드를 호출합니다.

currentTime() — 현재 시각의 UNIX 타임스탬프

Carbon::now()->getTimestamp()를 반환하는 심플한 래퍼입니다. secondsUntil()의 기준 시각으로 사용됩니다.
$now = $this->currentTime(); // int(UNIX タイムスタンプ)

runTimeForHumans() — 실행 시간을 사람이 읽기 쉬운 형식으로

microtime(true)로 기록한 시작 시각과 종료 시각의 차이를, 읽기 쉬운 문자열로 변환합니다.
$start = microtime(true);

// ... 처리 ...

echo $this->runTimeForHumans($start); // 例: "42.15ms" または "1s 234ms"
1000ms 미만은 42.15ms처럼 소수점 있는 밀리초, 1000ms 이상은 CarbonInterval의 forHumans() 단축 형식(1s 234ms 등)으로 반환합니다. 두 번째 인수에 종료 시각을 전달함으로써, 측정된 구간을 변환할 수도 있습니다.
$elapsed = $this->runTimeForHumans($start, $end);

패키지 개발에서의 활용

캐시 드라이버의 TTL 통일

put(key, value, ttl)ttl로서 int·DateInterval·DateTime 중 어느 것이라도 받아들이는 메서드를 만들 때 편리합니다.
use Illuminate\Support\InteractsWithTime;

class MyStore
{
    use InteractsWithTime;

    public function put(string $key, mixed $value, mixed $ttl): void
    {
        $seconds = $this->secondsUntil($ttl);

        // $seconds(int)で実際のストレージに保存
        $this->storage[$key] = [
            'value'      => $value,
            'expires_at' => $this->availableAt($ttl),
        ];
    }
}

콘솔 커맨드의 처리 시간 표시

Artisan 커맨드의 handle()에서 처리 시간을 사용자에게 표시할 때 활용할 수 있습니다.
use Illuminate\Console\Command;
use Illuminate\Support\InteractsWithTime;

class ProcessDataCommand extends Command
{
    use InteractsWithTime;

    public function handle(): void
    {
        $start = microtime(true);

        // ... 처리 ...

        $this->info("완료: {$this->runTimeForHumans($start)}");
    }
}

테스트용 InteractsWithTime

Illuminate\Foundation\Testing\Concerns\InteractsWithTime은 별개의 것이며, 테스트 케이스에서 시간을 조작하는 travel*() 메서드를 제공합니다(TestCase에 자동적으로 포함됩니다).
// テスト内で時間を進める(Testing\Concerns\InteractsWithTime)
$this->travel(5)->days();
$this->travelTo(now()->addMonth());
$this->travelBack();
Illuminate\Support\InteractsWithTime(이 페이지의 대상)과는 네임스페이스가 다르므로, 혼동하지 않도록 주의해 주세요.

정리

메서드반환값주요 용도
secondsUntil($delay)int남은 초 수의 취득
availableAt($delay)int유효 개시 타임스탬프의 계산
parseDateInterval($delay)DateTimeInterface|intDateInterval → Carbon으로의 변환
currentTime()int현재의 UNIX 타임스탬프
runTimeForHumans($start, $end)string실행 시간의 사람용 표시
인수로 int·DateInterval·DateTimeInterface 중 어느 것이라도 받아들이는 메서드를 만들고 싶은 경우, 이 트레이트를 use하는 것만으로 변환 로직을 다시 구현하지 않아도 됩니다.

관련 페이지

마지막 수정일 2026년 7월 13일