0Pricing
C# Academy · 강의

주기적 작업과 타이머

PeriodicTimer와 System.Threading.Timer로 반복 작업을 예약하고 취소를 원활하게 관리합니다.

주기적 작업과 타이머은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

반복 작업 예약

많은 백그라운드 서비스는 5분마다, 1시간마다 또는 매일처럼 정해진 일정에 따라 실행되어야 합니다. .NET은 여러 메커니즘을 제공합니다: PeriodicTimer(최신 방식), System.Threading.Timer(전통적인 방식), Quartz.NET(cron 기반)입니다.

PeriodicTimer: 최신 방식

PeriodicTimer(.NET 6에서 도입됨)는 async 메서드에서 사용하도록 설계되었습니다. 콜백 없이 정확한 일정에 따라 작동하며 취소와도 깔끔하게 통합됩니다.

public class MetricsCollectorService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));

        while (await timer.WaitForNextTickAsync(ct))
        {
            // Runs every 60 seconds
            await CollectMetricsAsync(ct);
        }
        // Loop exits cleanly when ct is cancelled
    }
}

PeriodicTimer와 Task.Delay 반복문의 비교

PeriodicTimer는 Task.Delay 반복문보다 우수합니다. 시작 시각을 기준으로 고정된 간격마다 작동하므로(시작 시각에 처리 시간을 더한 시점이 아님) 여러 번 반복해도 누적 오차가 발생하지 않습니다.

// Task.Delay loop — drifts! (interval = delay + work time)
while (!ct.IsCancellationRequested)
{
    await DoWorkAsync(ct); // takes 2 seconds
    await Task.Delay(5000, ct); // actual period: 7 seconds
}

// PeriodicTimer — no drift
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));
while (await timer.WaitForNextTickAsync(ct))
{
    await DoWorkAsync(ct); // period is still 5 seconds from start
}

System.Threading.Timer

System.Threading.Timer는 콜백을 사용하는 전통적인 스레드 풀 타이머입니다. 반복 모드와 단일 실행 모드를 모두 지원합니다. 콜백은 async를 지원하지 않는 스레드 풀 스레드에서 실행되므로 주의하세요.

public class LegacyTimerService : BackgroundService, IDisposable
{
    private Timer? _timer;

    protected override Task ExecuteAsync(CancellationToken ct)
    {
        // Fire immediately then every 10 seconds
        _timer = new Timer(DoWork, null,
            dueTime:  TimeSpan.Zero,
            period:   TimeSpan.FromSeconds(10));
        return Task.CompletedTask;
    }

    private void DoWork(object? state)
    {
        // Runs on thread pool — avoid async void here
        Console.WriteLine($"Timer fired: {DateTime.UtcNow}");
    }

    public override void Dispose() { _timer?.Dispose(); base.Dispose(); }
}

한 번만 실행되는 지연 작업

한 번만 실행되는 지연 작업에는 단일 틱으로 PeriodicTimer를 사용하거나, CancellationTokenSource.CancelAfter와 Task.Delay를 함께 사용하세요.

// Run once after a delay
public async Task ScheduleOnceAsync(TimeSpan delay, Func<Task> action, CancellationToken ct)
{
    await Task.Delay(delay, ct);
    await action();
}

// Or with CancellationToken:
var cts = new CancellationTokenSource(TimeSpan.FromHours(1));
try
{
    await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (OperationCanceledException)
{
    await RunScheduledJobAsync();
}

오류 처리를 적용한 PeriodicTimer

한 번의 실패로 다음 주기에 타이머가 다시 작동하지 않는 일이 없도록 각 틱의 작업을 항상 try/catch로 감싸세요.

protected override async Task ExecuteAsync(CancellationToken ct)
{
    using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));

    while (await timer.WaitForNextTickAsync(ct))
    {
        try
        {
            await SyncInventoryAsync(ct);
        }
        catch (Exception ex)
        {
            // Log but don't crash — next tick will retry
            _logger.LogError(ex, "Inventory sync failed");
        }
    }
}

시각 경계에 맞추기

특정 시각에 실행하려면(예: 매시 정각), 타이머를 시작하기 전에 다음 시각 경계까지의 초기 지연 시간을 계산하세요.

protected override async Task ExecuteAsync(CancellationToken ct)
{
    // Wait until the next full hour
    var now = DateTime.UtcNow;
    var nextHour = now.Date.AddHours(now.Hour + 1);
    var initialDelay = nextHour - now;

    await Task.Delay(initialDelay, ct);

    // Then tick every hour exactly
    using var timer = new PeriodicTimer(TimeSpan.FromHours(1));

    await RunJobAsync(ct); // run at the first tick
    while (await timer.WaitForNextTickAsync(ct))
        await RunJobAsync(ct);
}

동시 틱 실행 방지

작업이 타이머의 한 주기보다 오래 걸릴 수 있다면 SemaphoreSlim으로 동시 실행을 방지하거나, 아직 실행 중이면 해당 틱을 건너뛰세요.

private readonly SemaphoreSlim _lock = new(1, 1);

protected override async Task ExecuteAsync(CancellationToken ct)
{
    using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));

    while (await timer.WaitForNextTickAsync(ct))
    {
        // Skip if previous tick is still running
        if (!await _lock.WaitAsync(0, ct))
        {
            _logger.LogWarning("Skipping tick — previous still running");
            continue;
        }
        try { await DoWorkAsync(ct); }
        finally { _lock.Release(); }
    }
}

분산 서비스의 무작위 지연

여러 서비스 인스턴스가 동시에 시작될 때 초기 지연에 무작위 지연을 추가하면 공유 리소스에 요청이 한꺼번에 몰리는 문제를 방지할 수 있습니다.

protected override async Task ExecuteAsync(CancellationToken ct)
{
    // Add jitter: 0-5 seconds random delay on startup
    var jitter = TimeSpan.FromSeconds(Random.Shared.NextDouble() * 5);
    await Task.Delay(jitter, ct);

    using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
    while (await timer.WaitForNextTickAsync(ct))
        await RunJobAsync(ct);
}

실전: 캐시 새로 고침 서비스

지터와 오류 복구를 적용하여 10분마다 분산 캐시를 새로 고치는 주기적 서비스입니다.

public class CacheRefreshService : BackgroundService
{
    private readonly IServiceScopeFactory _factory;
    private readonly ILogger<CacheRefreshService> _log;

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        // Spread startups across instances
        await Task.Delay(TimeSpan.FromSeconds(Random.Shared.Next(0, 30)), ct);

        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
        while (await timer.WaitForNextTickAsync(ct))
        {
            try
            {
                using var scope = _factory.CreateScope();
                var cache = scope.ServiceProvider.GetRequiredService<ICacheService>();
                await cache.RefreshAllAsync(ct);
                _log.LogInformation("Cache refreshed at {Time}", DateTime.UtcNow);
            }
            catch (Exception ex) { _log.LogError(ex, "Cache refresh failed"); }
        }
    }
}

빠른 확인

반복 작업에서 PeriodicTimer가 Task.Delay 반복문보다 선호되는 이유는 무엇입니까?

복습: 반복 작업 및 타이머

핵심 요점:

  • PeriodicTimer: async, 취소 인식, 누적 오차 없음 — 최신 방식
  • System.Threading.Timer: 콜백 기반, 기존 코드와 통합할 때 유용
  • 오류로 인해 타이머가 중지되지 않도록 각 틱의 작업을 try/catch로 감쌉니다
  • 분산 인스턴스에 지터를 추가하여 요청이 한꺼번에 몰리는 현상을 방지합니다
  • 이전 틱이 아직 실행 중이면 SemaphoreSlim을 사용하여 다음 틱을 건너뜁니다
  • 틱을 시각 경계에 맞추도록 초기 지연 시간을 계산합니다

자주 묻는 질문

“주기적 작업과 타이머” 강의는 무료인가요?

네 — “주기적 작업과 타이머” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“주기적 작업과 타이머”에서 뭘 배우나요?

PeriodicTimer와 System.Threading.Timer로 반복 작업을 예약하고 취소를 원활하게 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

C# Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“주기적 작업과 타이머” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. IHostedService와 BackgroundService
  2. Worker Service 프로젝트
  3. 주기적 작업과 타이머
  4. Quartz.NET 예약 작업
← C# Academy(으)로 돌아가기