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
- 継承
- 実装
例
次の例では、 System.Timers.Timer
2 秒 (2000 ミリ秒) ごとにイベントを発生させるオブジェクトをインスタンス化し、イベント Timer.Elapsed のイベントハンドラーを設定して、タイマーを開始します。 イベントハンドラーは、発生するたびにプロパティの値を表示し 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コンポーネントは、 Elapsed プロパティのミリ秒数が経過した後にアプリケーションでイベントを発生させる、サーバーベースのタイマーです Interval 。 オブジェクトを構成し 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 ます。 このイベントを処理して、必要な処理を実行できます。 たとえば、販売注文をデータベースに継続的にポストするオンライン販売アプリケーションがあるとします。 出荷の指示をコンパイルするサービスは、各注文を個別に処理するのではなく、注文のバッチで動作します。 を使用すると、 Timer バッチ処理を30分ごとに開始できます。
重要
System.string クラスには、システムクロックと同じ解決策があります。 これは、 Elapsed Interval プロパティがシステムクロックの解像度よりも小さい場合に、システムクロックの解決によって定義された間隔でイベントを発生させることを意味します。 詳細については、Interval プロパティを参照してください。
がに設定されている場合、 AutoReset false
オブジェクトは、 System.Timers.Timer Elapsed 最初の経過後に1回だけイベントを発生させ Interval ます。 によって定義された間隔で定期的にイベントを発生させるには、を Elapsed Interval に設定し AutoReset true
ます。これは既定値です。
コンポーネントは、イベント Timer のイベントハンドラーによってスローされたすべての例外をキャッチし、抑制し Elapsed ます。 この動作は、.NET Framework の今後のリリースで変更される可能性があります。 ただし、これは非同期に実行され、 await
演算子 (C# の場合) または Await
演算子 (Visual Basic) を含むイベントハンドラーには当てはまりません。 これらのイベントハンドラーでスローされる例外は、次の例に示すように、呼び出し元のスレッドに反映されます。 非同期メソッドでスローされる例外の詳細については、「 例外処理」を参照してください。
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プロパティがの場合 null
、 Elapsed イベントはスレッドで発生し ThreadPool ます。 イベントの処理時間が Elapsed よりも長くなる Interval と、別のスレッドでイベントが再度発生する可能性があり ThreadPool ます。 この場合、イベントハンドラーは再入可能である必要があります。
注意
イベント処理メソッドは、別のスレッドがメソッドを呼び出したとき、 Stop またはプロパティをに設定するときに、1つのスレッドで実行されることがあり Enabled false
ます。 これにより、 Elapsed タイマーが停止した後にイベントが発生する可能性があります。 コードの使用例、Stopメソッドは、この競合状態を回避するために 1 つのメソッドを示しています。
がでない場合でも、 SynchronizingObject null
Elapsed メソッドまたはメソッドが呼び出された後、またはプロパティがに設定された後に、イベントが発生する可能性があり Dispose Stop Enabled ます。これは、イベントを発生させる false
シグナル Elapsed が常にスレッドプールのスレッドで実行するためにキューに入れられるためです。 この競合状態がのイベント ハンドラーを示すフラグを設定するには解決するのには 1 つのメソッド、Elapsed後続のイベントを無視するイベントです。
ユーザーインターフェイス System.Timers.Timer 要素にタイマーを配置せずに、フォームやコントロールなどのユーザーインターフェイス要素でクラスを使用する場合は、を含むフォームまたはコントロールをプロパティに割り当てて、 Timer SynchronizingObject イベントがユーザーインターフェイススレッドにマーシャリングされるようにします。
のインスタンスの既定のプロパティ値の一覧につい Timer ては、コンストラクターを参照してください Timer 。
ヒント
.NET にはという4つのクラスが含まれており Timer
、それぞれが異なる機能を提供していることに注意してください。
- System.Timers.Timer (このトピック): 一定の間隔でイベントを発生します。 クラスは、マルチスレッド環境でサーバーベースまたはサービスコンポーネントとして使用することを目的としています。ユーザーインターフェイスはなく、実行時には表示されません。
- System.Threading.Timer: スレッドプールのスレッドで、一定の間隔で単一のコールバックメソッドを実行します。 コールバックメソッドは、タイマーがインスタンス化され、変更できないときに定義されます。 クラスと同様に 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) |
events
Disposed |
Dispose() メソッドの呼び出しによってコンポーネントが破棄されるときに発生します。 (継承元 Component) |
Elapsed |
間隔が経過すると発生します。 |
適用対象
スレッド セーフ
static
この型のすべてのパブリックメンバーは、スレッドセーフです。 インスタンス メンバーの場合は、スレッド セーフであるとは限りません。