다음을 통해 공유


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 개체는 필요한 한 범위에 유지되도록 클래스 수준에서 선언됩니다. 그런 다음 이벤트를 Elapsed 처리하여 정기적인 처리를 제공할 수 있습니다. 예를 들어 하루 24시간, 주 7일을 계속 실행해야 하는 중요한 서버가 있다고 가정해 보겠습니다. 개체를 사용하여 Timer 서버를 주기적으로 확인하고 시스템이 실행 중인지 확인하는 서비스를 만들 수 있습니다. 시스템이 응답하지 않으면 서비스에서 서버를 다시 시작하거나 관리자에게 알릴 수 있습니다.

중요합니다

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

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

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

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

중요합니다

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

메모

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

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

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()

속성이 SynchronizingObjectnull면 스레드에서 ElapsedThreadPool 이벤트가 발생합니다. 이벤트 처리가 ElapsedInterval오래 지속되는 경우 다른 ThreadPool 스레드에서 이벤트가 다시 발생할 수 있습니다. 이 경우 이벤트 처리기는 재진입해야 합니다.

메모

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

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

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

인스턴스 Timer의 기본 속성 값 목록은 생성자를 참조 Timer 하세요.

팁 (조언)

.NET에는 각각 다른 기능을 제공하는 네 개의 클래스가 포함되어 Timer있습니다.

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

생성자

Name Description
Timer()

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

Timer(Double)

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

Timer(TimeSpan)

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

속성

Name Description
AutoReset

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

CanRaiseEvents

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

(다음에서 상속됨 Component)
Container

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

(다음에서 상속됨 Component)
DesignMode

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

(다음에서 상속됨 Component)
Enabled

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

Events

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

(다음에서 상속됨 Component)
Interval

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

Site

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

SynchronizingObject

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

메서드

Name Description
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()

로 설정 Enabled 하여 이벤트 발생 Elapsed 을 시작합니다true.

Stop()

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

ToString()

String(있는 경우)의 Component이름을 포함하는 값을 반환합니다. 이 메서드는 재정의해서는 안 됩니다.

(다음에서 상속됨 Component)

이벤트

Name Description
Disposed

구성 요소가 메서드 호출에 Dispose() 의해 삭제될 때 발생합니다.

(다음에서 상속됨 Component)
Elapsed

간격이 경과할 때 발생합니다.

적용 대상

스레드 보안

이 형식의 모든 공용 static 멤버는 스레드로부터 안전합니다. 모든 인스턴스 멤버는 스레드로부터 안전하게 보호되지 않습니다.

추가 정보