Timer クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
一定の間隔の経過後にイベントを生成します。オプションとして、反復イベントを生成することもできます。
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 秒 (2,000 ミリ秒) ごとにイベントをTimer.Elapsed発生させ、イベントのイベント ハンドラーを設定し、タイマーを開始するオブジェクトをインスタンス化System.Timers.Timer
します。 イベント ハンドラーは、プロパティが発生するたびにプロパティの 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...
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サーバー ベースのタイマーです。 イベントを Timer 1 回だけ発生させるか、プロパティを使用して繰り返し発生するようにオブジェクトを AutoReset 構成できます。 通常、 Timer オブジェクトは必要な限りスコープ内に留まるように、クラス レベルで宣言されます。 その後、そのイベントを Elapsed 処理して、通常の処理を提供できます。 たとえば、1 日 24 時間、週 7 日実行し続ける必要がある重要なサーバーがあるとします。 オブジェクトを使用してサーバーを Timer 定期的にチェックし、システムが稼働していることを確認するサービスを作成できます。 システムが応答していない場合、サービスはサーバーの再起動を試みるか、管理者に通知する可能性があります。
重要
この Timer クラスは、.NET Standard 1.6 以前のバージョンなど、すべての .NET 実装とバージョンで使用できるわけではありません。 このような場合は、代わりにクラスを System.Threading.Timer 使用できます。
この型は IDisposable インターフェイスを実装します。 型の使用が完了したら、直接的または間接的に型を破棄する必要があります。 直接的に型を破棄するには、try
/catch
ブロック内で Dispose メソッドを呼び出します。 間接的に型を破棄するには、using
(C# の場合) または Using
(Visual Basic 言語) などの言語構成要素を使用します。 詳細については、IDisposable インターフェイスに関するトピック内の「IDisposable を実装するオブジェクトの使用」セクションを参照してください。
サーバー ベース System.Timers.Timer のクラスは、マルチスレッド環境のワーカー スレッドで使用するように設計されています。 サーバー タイマーは、発生したElapsedイベントを処理するためにスレッド間を移動できるため、時間にイベントを発生させるWindowsタイマーよりも精度が高くなります。
コンポーネントは System.Timers.Timer 、プロパティの Elapsed 値 (ミリ秒単位) に基づいてイベントを Interval 発生させます。 このイベントを処理して、必要な処理を実行できます。 たとえば、販売注文をデータベースに継続的に転記するオンライン販売アプリケーションがあるとします。 出荷手順をコンパイルするサービスは、各注文を個別に処理するのではなく、注文のバッチで動作します。 a を Timer 使用して、バッチ処理を 30 分ごとに開始できます。
重要
System.Timers.Timer クラスの解像度は、システム クロックと同じです。 つまり、プロパティが Elapsed システム クロックの解像度よりも小さい場合 Interval 、システム クロックの解像度によって定義された間隔でイベントが発生します。 詳細については、Interval プロパティを参照してください。
注意
使用されるシステム クロックは 、GetTickCount で使用されるのと同じクロックであり、 timeBeginPeriod と timeEndPeriod で行われた変更の影響を受けません。
に設定するとAutoReset、オブジェクトはSystem.Timers.Timer、最初IntervalのイベントがElapsed経過した後、1 回だけイベントを発生false
させます。 によって定義されたInterval間隔でイベントをElapsed定期的に発生させ続けるには、既定値に設定AutoResettrue
します。
コンポーネントは Timer 、イベントのイベント ハンドラーによってスローされるすべての例外を Elapsed キャッチして抑制します。 この動作は、.NET Frameworkの今後のリリースで変更される可能性があります。 ただし、これは非同期的に実行され、演算子 (C#では) またはAwait
演算子 (Visual Basic) を含むawait
イベント ハンドラーには当てはまらないことに注意してください。 これらのイベント ハンドラーでスローされた例外は、次の例に示すように、呼び出し元のスレッドに反映されます。 非同期メソッドでスローされる例外の詳細については、「 例外処理」を参照してください。
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()
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()
プロパティが指定されているSynchronizingObject場合、Elapsednull
イベントはスレッドで発生しますThreadPool。 イベントの処理が Elapsed 長く続く Interval場合は、別 ThreadPool のスレッドでイベントが再び発生する可能性があります。 この状況では、イベント ハンドラーは再入可能である必要があります。
注意
イベント処理メソッドは、別のスレッドがメソッドを呼び出Stopすか、プロパティfalse
を設定Enabledすると同時に、1 つのスレッドで実行される可能性があります。 これにより、タイマーが Elapsed 停止した後にイベントが発生する可能性があります。 コードの使用例、Stopメソッドは、この競合状態を回避するために 1 つのメソッドを示しています。
そうでないnull
場合SynchronizingObjectでも、Elapsedイベントは、イベントがDispose呼び出された後、Stopまたはプロパティが設定された後Enabledにfalse
発生する可能性があります。イベントを発生させるElapsedシグナルは常にスレッド プール スレッドで実行するためにキューに入れられます。 この競合状態がのイベント ハンドラーを示すフラグを設定するには解決するのには 1 つのメソッド、Elapsed後続のイベントを無視するイベントです。
フォームやコントロールなどのユーザー インターフェイス要素でクラスを使用 System.Timers.Timer する場合は、そのユーザー インターフェイス要素にタイマーを配置せずに、プロパティを含む Timer フォームまたはコントロールを SynchronizingObject 割り当てて、イベントがユーザー インターフェイス スレッドにマーシャリングされるようにします。
インスタンスの既定のプロパティ値の Timer一覧については、コンストラクターを Timer 参照してください。
ヒント
.NET には、それぞれ異なる機能を提供する 4 つのクラスが含 Timer
まれています。
- System.Timers.Timer (このトピック): 一定の間隔でイベントを発生します。 このクラスは、マルチスレッド環境でサーバー ベースまたはサービス コンポーネントとして使用することを目的としています。ユーザー インターフェイスがなく、実行時には表示されません。
- System.Threading.Timer: スレッド プール スレッドで 1 つのコールバック メソッドを一定の間隔で実行します。 コールバック メソッドは、タイマーがインスタンス化されるときに定義され、変更できません。 クラスと同様に System.Timers.Timer 、このクラスは、マルチスレッド環境でサーバー ベースまたはサービス コンポーネントとして使用することを目的としています。ユーザー インターフェイスがなく、実行時には表示されません。
- System.Windows.Forms.Timer: 一定の間隔でイベントを発生させる Windows フォーム コンポーネント。 このコンポーネントにはユーザー インターフェイスがなく、シングルスレッド環境で使用するように設計されています。
- System.Web.UI.Timer(.NET Frameworkのみ): 一定の間隔で非同期または同期 Web ページのポストバックを実行する ASP.NET コンポーネント。
コンストラクター
Timer() |
Timer クラスの新しいインスタンスを初期化し、すべてのプロパティを初期値に設定します。 |
Timer(Double) |
プロパティ
AutoReset |
Timer が Elapsed イベントを一度のみ発生させる ( |
CanRaiseEvents |
コンポーネントがイベントを発生させることがきるかどうかを示す値を取得します。 (継承元 Component) |
Container |
IContainer を含む Component を取得します。 (継承元 Component) |
DesignMode |
Component が現在デザイン モードかどうかを示す値を取得します。 (継承元 Component) |
Enabled | |
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() | |
Stop() | |
ToString() |
Component の名前 (存在する場合) を格納する String を返します。 このメソッドはオーバーライドできません。 (継承元 Component) |
イベント
Disposed |
Dispose() メソッドの呼び出しによってコンポーネントが破棄されるときに発生します。 (継承元 Component) |
Elapsed |
間隔が経過すると発生します。 |
適用対象
スレッド セーフ
この型のパブリック static
メンバーはすべてスレッド セーフです。 インスタンス メンバーの場合は、スレッド セーフであるとは限りません。