C# 6.0 이후부터는 주기적으로 작업을 실행하는 다양한 방법이 있지만, .NET 6부터 도입된 PeriodicTimer는 간편하고 효율적인 주기적 작업 처리 도구입니다.
1. PeriodicTimer란?
PeriodicTimer는 지정된 간격으로 반복 작업을 실행할 때 사용하는 타이머입니다. 기존 타이머에 비해 비동기 환경에서 사용하기 편리하며, 작업 간격이 정확한 점이 특징입니다.
2. 기본 사용법
PeriodicTimer는 async/await 패턴과 잘 어울리며, 다음과 같이 사용할 수 있습니다.
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
while (await timer.WaitForNextTickAsync())
{
Console.WriteLine($"작업 실행 시간: {DateTime.Now}");
}
}
}
3. 주의할 점
PeriodicTimer는 무한 루프로 실행되므로, 적절한 취소 토큰(CancellationToken)을 이용해 종료 시점을 제어하는 것이 좋습니다.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
try
{
while (await timer.WaitForNextTickAsync(cts.Token))
{
Console.WriteLine($"주기적 작업 실행: {DateTime.Now}");
}
}
catch (OperationCanceledException)
{
Console.WriteLine("작업이 취소되었습니다.");
}
이처럼 PeriodicTimer를 활용하면 간단하게 주기적 작업을 구현할 수 있습니다.
'C#' 카테고리의 다른 글
| C# GCHandle로 관리 객체 고정(Pinning)하기 (0) | 2026.07.29 |
|---|---|
| C# Semaphore와 Mutex 차이 및 선택 기준 (0) | 2026.07.28 |
| C# Random.Shared와 안전한 난수 생성 전략 (0) | 2026.07.27 |
| C# UTF8String 리터럴과 UTF-8 문자열 처리 최적화 (0) | 2026.07.27 |
| C# init 접근자를 활용한 불변 객체 설계 (0) | 2026.07.26 |