Timer 클래스

정의

반복 이벤트를 생성하는 옵션으로 설정된 간격 후 이벤트를 생성합니다.

public ref class Timer : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public class Timer : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type Timer = class
    inherit Component
    interface ISupportInitialize
Public Class Timer
Inherits Component
Implements ISupportInitialize
상속
구현

예제

다음 예제에서는 2초마다 이벤트를 발생 Timer.Elapsed 시키는 개체를 인스턴스화 System.Timers.Timer 하고(2,000밀리초) 이벤트에 대한 이벤트 처리기를 설정하고 타이머를 시작합니다. 이벤트 처리기는 발생할 때마다 속성의 ElapsedEventArgs.SignalTime 값을 표시합니다.

using System;
using System.Timers;

public class Example
{
   private static System.Timers.Timer aTimer;
   
   public static void Main()
   {
      SetTimer();

      Console.WriteLine("\nPress the Enter key to exit the application...\n");
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
      Console.ReadLine();
      aTimer.Stop();
      aTimer.Dispose();
      
      Console.WriteLine("Terminating the application...");
   }

   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       The Elapsed event was raised at 09:40:43.132
//       The Elapsed event was raised at 09:40:45.133
//       The Elapsed event was raised at 09:40:47.148
//
//       Terminating the application...
open System
open System.Timers

let onTimedEvent source (e: ElapsedEventArgs) =
    printfn $"""The Elapsed event was raised at {e.SignalTime.ToString "HH:mm:ss.fff"}"""

// Create a timer with a two second interval.
let aTimer = new Timer 2000
// Hook up the Elapsed event for the timer. 
aTimer.Elapsed.AddHandler onTimedEvent
aTimer.AutoReset <- true
aTimer.Enabled <- true

printfn "\nPress the Enter key to exit the application...\n"
printfn $"""The application started at {DateTime.Now.ToString "HH:mm:ss.fff"}"""
stdin.ReadLine() |> ignore
aTimer.Stop()
aTimer.Dispose()

printfn "Terminating the application..."

// The example displays output like the following:
//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       The Elapsed event was raised at 09:40:43.132
//       The Elapsed event was raised at 09:40:45.133
//       The Elapsed event was raised at 09:40:47.148
//
//       Terminating the application...
Imports System.Timers

Public Module Example
    Private aTimer As System.Timers.Timer

    Public Sub Main()
        SetTimer()

      Console.WriteLine("{0}Press the Enter key to exit the application...{0}",
                        vbCrLf)
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}",
                        DateTime.Now)
      Console.ReadLine()
      aTimer.Stop()
      aTimer.Dispose()

      Console.WriteLine("Terminating the application...")
    End Sub

    Private Sub SetTimer()
        ' Create a timer with a two second interval.
        aTimer = New System.Timers.Timer(2000)
        ' Hook up the Elapsed event for the timer. 
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
        aTimer.AutoReset = True
        aTimer.Enabled = True
    End Sub

    ' The event handler for the Timer.Elapsed event. 
    Private Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime)
    End Sub 
End Module
' The example displays output like the following:
'       Press the Enter key to exit the application...
'
'       The application started at 09:40:29.068
'       The Elapsed event was raised at 09:40:31.084
'       The Elapsed event was raised at 09:40:33.100
'       The Elapsed event was raised at 09:40:35.100
'       The Elapsed event was raised at 09:40:37.116
'       The Elapsed event was raised at 09:40:39.116
'       The Elapsed event was raised at 09:40:41.117
'       The Elapsed event was raised at 09:40:43.132
'       The Elapsed event was raised at 09:40:45.133
'       The Elapsed event was raised at 09:40:47.148
'
'       Terminating the application...

설명

Timer 구성 요소는 속성의 밀리초 수가 경과한 후 애플리케이션에서 Interval 이벤트를 발생 Elapsed 시키는 서버 기반 타이머입니다. 속성을 사용하여 이벤트를 한 번만 발생하거나 반복적으로 발생하도록 개체를 AutoReset 구성할 Timer 수 있습니다. 일반적으로 Timer 개체는 클래스 수준에서 선언되므로 필요한 한 scope 유지됩니다. 그런 다음 이벤트를 Elapsed 처리하여 정기적인 처리를 제공할 수 있습니다. 예를 들어, 유지 해야 하는 중요 한 서버가 있는 24 시간 내내 하루를 실행 합니다. 개체를 사용하여 Timer 서버를 주기적으로 검사 시스템이 실행 중인지 확인하는 서비스를 만들 수 있습니다. 시스템이 응답 하지 않는 경우 서비스 서버를 다시 시작 하거나 관리자에 게 알리는를 시도할 수 있습니다.

중요

클래스는 Timer .NET Standard 1.6 이하 버전과 같은 모든 .NET 구현 및 버전에 사용할 수 없습니다. 이러한 경우 클래스를 대신 사용할 System.Threading.Timer 수 있습니다.

이 형식이 구현 하는 IDisposable 인터페이스입니다. 형식을 사용 하 여 마쳤으면 직접 또는 간접적으로의 삭제 해야 있습니다. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try/catch 블록입니다. 삭제 하지 직접, 언어 구문 같은 사용 using (C#에서) 또는 Using (Visual Basic에서는). 자세한 내용은 "를 사용 하는 개체는 구현 IDisposable" 섹션을 참조 하세요.를 IDisposable 인터페이스 항목입니다.

서버 기반 System.Timers.Timer 클래스는 다중 스레드 환경에서 작업자 스레드와 함께 사용하도록 설계되었습니다. 발생 한 처리 서버 타이머 스레드로 이동할 수 Elapsed 이벤트에 Windows 타이머 시간에 이벤트를 발생 시키는 것 보다 더 정확 합니다.

System.Timers.Timer 구성 요소는 속성의 Elapsed 값(밀리초)Interval을 기준으로 이벤트를 발생합니다. 이 이벤트를 처리하여 필요한 처리를 수행할 수 있습니다. 예를 들어 판매 주문을 데이터베이스에 지속적으로 게시하는 온라인 판매 애플리케이션이 있다고 가정해 보겠습니다. 배송 지침을 컴파일하는 서비스는 각 주문을 개별적으로 처리하는 대신 주문 일괄 처리로 작동합니다. 를 Timer 사용하여 30분마다 일괄 처리를 시작할 수 있습니다.

중요

System.Timers.Timer 클래스의 해상도는 시스템 클록과 동일합니다. 즉, 속성이 Elapsed 시스템 클록의 해상도보다 작으면 Interval 시스템 클록의 해상도로 정의된 간격으로 이벤트가 발생합니다. 자세한 내용은 Interval 속성을 참조하세요.

참고

사용되는 시스템 클록은 GetTickCount에서 사용하는 것과 동일한 클록으로, timeBeginPeriodtimeEndPeriod로 변경된 내용의 영향을 받지 않습니다.

가 로 설정된 경우 AutoReset 개체는 System.Timers.Timer 첫 번째 Interval 가 경과한 후 이벤트를 한 번만 발생 Elapsedfalse합니다. 에서 정의IntervalElapsed 간격으로 이벤트를 정기적으로 발생하려면 를 로 설정합니다 AutoResettrue. 이 기본값입니다.

Timer 구성 요소는 이벤트에 대한 Elapsed 이벤트 처리기에서 throw된 모든 예외를 catch하고 표시하지 않습니다. 이 동작은 .NET Framework 이후 릴리스에서 변경될 수 있습니다. 그러나 비동기적으로 실행되고 연산자(C#) 또는 Await 연산자(Visual Basic의 경우)를 포함하는 await 이벤트 처리기의 경우는 그렇지 않습니다. 다음 예제와 같이 이러한 이벤트 처리기에서 throw된 예외는 호출 스레드로 다시 전파됩니다. 비동기 메서드에서 throw된 예외에 대한 자세한 내용은 예외 처리를 참조하세요.

using System;
using System.Threading.Tasks;
using System.Timers;

class Example
{
   static void Main()
   {
      Timer timer = new Timer(1000);
      timer.Elapsed += async ( sender, e ) => await HandleTimer();
      timer.Start();
      Console.Write("Press any key to exit... ");
      Console.ReadKey();
   }

   private static Task HandleTimer()
   {
     Console.WriteLine("\nHandler not implemented..." );
     throw new NotImplementedException();
   }
}
// The example displays output like the following:
//   Press any key to exit...
//   Handler not implemented...
//   
//   Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
//      at Example.HandleTimer()
//      at Example.<<Main>b__0>d__2.MoveNext()
//   --- End of stack trace from previous location where exception was thrown ---
//      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
//      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
//      at System.Threading.ThreadPoolWorkQueue.Dispatch()
open System
open System.Threading.Tasks
open System.Timers

let handleTimer () =
    printfn "\nHandler not implemented..."
    raise (NotImplementedException()): Task

let timer = new Timer 1000
timer.Elapsed.AddHandler(fun sender e -> task { do! handleTimer () } |> ignore)
timer.Start()
printf "Press any key to exit... "
Console.ReadKey() |> ignore

// The example displays output like the following:
//   Press any key to exit...
//   Handler not implemented...
//
//   Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
//      at Example.HandleTimer()
//      at Example.<<Main>b__0>d__2.MoveNext()
//   --- End of stack trace from previous location where exception was thrown ---
//      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
//      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
//      at System.Threading.ThreadPoolWorkQueue.Dispatch()
Imports System.Threading.Tasks
Imports System.Timers

Public Module Example
   Public Sub Main()
      Dim timer As New Timer(1000)  
      AddHandler timer.Elapsed, AddressOf Example.HandleTimer     
      'timer.Elapsed = Async ( sender, e ) => await HandleTimer()
      timer.Start()
      Console.Write("Press any key to exit... ")
      Console.ReadKey()
   End Sub

   Private Async Sub HandleTimer(sender As Object, e As EventArgs)
      Await Task.Run(Sub()
                        Console.WriteLine()
                        Console.WriteLine("Handler not implemented..." )
                        Throw New NotImplementedException()
                     End Sub)   
   End Sub
End Module
' The example displays output like the following:
'   Press any key to exit...
'   Handler not implemented...
'   
'   Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
'      at Example._Lambda$__1()
'      at System.Threading.Tasks.Task.Execute()
'   --- End of stack trace from previous location where exception was thrown ---
'      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
'      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
'      at Example.VB$StateMachine_0_HandleTimer.MoveNext()
'   --- End of stack trace from previous location where exception was thrown ---
'      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
'      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
'      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
'      at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
'      at System.Threading.ThreadPoolWorkQueue.Dispatch()

속성null이 이 SynchronizingObjectElapsed 면 이벤트가 스레드에서 ThreadPool 발생합니다. 이벤트 처리가 Elapsed 보다 Interval오래 지속되는 경우 다른 ThreadPool 스레드에서 이벤트가 다시 발생할 수 있습니다. 이 경우 이벤트 처리기를 다시 입력해야 합니다.

참고

이벤트 처리 메서드는 다른 스레드가 메서드를 호출 Stop 하거나 속성을 로 설정하는 Enabled 동시에 한 스레드에서 실행될 false수 있습니다. 이로 인해 타이머가 Elapsed 중지된 후 이벤트가 발생할 수 있습니다. 메서드의 Stop 예제 코드는 이 경합 상태를 방지하는 한 가지 방법을 보여줍니다.

가 이 아니 nullElapsed 더라도 SynchronizingObject 이벤트를 발생 Elapsed 하려면 false신호는 항상 스레드 풀 스레드에서 Dispose 실행 하기 위해 큐에 있기 때문에 또는 메서드가 호출 된 후 또는 Stop 속성이 로 설정 된 후 Enabled 이벤트가 발생할 수 있습니다. 이 경합 상태를 resolve 한 가지 방법은 이벤트 처리기에 후속 이벤트를 무시하도록 지시하는 플래그를 Elapsed 설정하는 것입니다.

해당 사용자 인터페이스 요소에 타이머를 System.Timers.Timer 배치하지 않고 폼 또는 컨트롤과 같은 사용자 인터페이스 요소와 함께 클래스를 사용하는 경우 이벤트가 사용자 인터페이스 스레드로 마샬링되도록 속성에 이 포함된 TimerSynchronizingObject 폼이나 컨트롤을 할당합니다.

의 instance Timer대한 기본 속성 값 목록은 생성자를 참조 Timer 하세요.

.NET에는 라는 Timer4개의 클래스가 포함되어 있으며, 각 클래스는 서로 다른 기능을 제공합니다.

  • System.Timers.Timer (이 항목): 정기적으로 이벤트를 발생합니다. 클래스는 다중 스레드 환경에서 서버 기반 또는 서비스 구성 요소로 사용하기 위한 것입니다. 사용자 인터페이스가 없으며 런타임에 표시되지 않습니다.
  • System.Threading.Timer: 스레드 풀 스레드에서 정기적으로 단일 콜백 메서드를 실행합니다. 콜백 메서드는 타이머가 인스턴스화되어 변경할 수 없을 때 정의됩니다. 클래스와 System.Timers.Timer 마찬가지로 이 클래스는 다중 스레드 환경에서 서버 기반 또는 서비스 구성 요소로 사용하기 위한 것입니다. 사용자 인터페이스가 없고 런타임에 표시되지 않습니다.
  • System.Windows.Forms.Timer: 이벤트를 정기적으로 발생시키는 Windows Forms 구성 요소입니다. 이 구성 요소에는 사용자 인터페이스가 없으며, 단일 스레드 환경에서 사용하도록 설계되었습니다.
  • System.Web.UI.Timer(.NET Framework만 해당): 비동기 또는 동기 웹 페이지 포스트백을 정기적으로 수행하는 ASP.NET 구성 요소입니다.

생성자

Timer()

Timer 클래스의 새 인스턴스를 초기화하고 모든 속성을 각각의 초기 값으로 설정합니다.

Timer(Double)

Timer 클래스의 새 인스턴스를 초기화하고 Interval 속성을 지정된 시간(밀리초)으로 설정합니다.

Timer(TimeSpan)

클래스의 새 instance Timer 초기화하여 속성을 지정된 기간으로 설정합니다Interval.

속성

AutoReset

Timer에서 Elapsed 이벤트를 한 번만(false) 발생시켜야 하는지 반복해서(true) 발생시켜야 하는지 나타내는 부울을 가져오거나 설정합니다.

CanRaiseEvents

구성 요소가 이벤트를 발생시킬 수 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Component)
Container

IContainer을 포함하는 Component를 가져옵니다.

(다음에서 상속됨 Component)
DesignMode

Component가 현재 디자인 모드인지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Component)
Enabled

Timer에서 Elapsed 이벤트를 발생시켜야 하는지 여부를 나타내는 값을 가져오거나 설정합니다.

Events

Component에 연결된 이벤트 처리기의 목록을 가져옵니다.

(다음에서 상속됨 Component)
Interval

Elapsed 이벤트를 발생시킬 간격(밀리초)을 가져오거나 설정합니다.

Site

디자인 모드에서 Timer를 컨테이너에 바인딩하는 사이트를 가져오거나 설정합니다.

SynchronizingObject

시간 간격이 경과할 때 발행되는 이벤트 처리기 호출을 마샬링하는 데 사용되는 개체를 가져오거나 설정합니다.

메서드

BeginInit()

폼에 사용되거나 다른 구성 요소에서 사용하는 Timer의 런타임 초기화를 시작합니다.

Close()

Timer에서 사용하는 리소스를 해제합니다.

CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
Dispose()

Component에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 Component)
Dispose(Boolean)

현재 Timer에서 사용하는 모든 리소스를 해제합니다.

EndInit()

폼에 사용되거나 다른 구성 요소에서 사용하는 Timer의 런타임 초기화를 마칩니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.

(다음에서 상속됨 MarshalByRefObject)
GetService(Type)

Component 또는 해당 Container에서 제공하는 서비스를 나타내는 개체를 반환합니다.

(다음에서 상속됨 Component)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
InitializeLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.

(다음에서 상속됨 MarshalByRefObject)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
Start()

Enabledtrue로 설정하여 Elapsed 이벤트를 발생시킵니다.

Stop()

Enabledfalse로 설정하여 Elapsed 이벤트 발생을 중지합니다.

ToString()

Component의 이름이 포함된 String을 반환합니다(있는 경우). 이 메서드는 재정의할 수 없습니다.

(다음에서 상속됨 Component)

이벤트

Disposed

Dispose() 메서드를 호출하여 구성 요소를 삭제할 때 발생합니다.

(다음에서 상속됨 Component)
Elapsed

간격이 경과하면 발생합니다.

적용 대상

스레드 보안

모든 공용 static 이 형식의 멤버는 스레드로부터 안전 합니다. 인스턴스 구성원은 스레드로부터의 안전성이 보장되지 않습니다.

추가 정보