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
- 継承
- 実装
例
次の例では、Timer.Elapsed イベントを 2 秒 (2,000 ミリ秒) ごとに発生させ、イベントのイベント ハンドラーを設定してタイマーを開始する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...
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 イベントを発生させるサーバー ベースのタイマーです。 Timer オブジェクトを構成して、イベントを 1 回だけ発生させたり、AutoReset プロパティを使用して繰り返し発生させたりすることができます。 通常、 Timer オブジェクトは、必要な限りスコープ内に保持されるように、クラス レベルで宣言されます。 その後、その Elapsed イベントを処理して、通常の処理を提供できます。 たとえば、24 時間、週 7 日実行し続ける必要がある重要なサーバーがあるとします。 Timer オブジェクトを使用してサーバーを定期的にチェックし、システムが稼働していることを確認するサービスを作成できます。 システムが応答していない場合、サービスはサーバーの再起動を試みるか、管理者に通知する可能性があります。
Important
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 コンポーネントは、Interval プロパティの値 (ミリ秒) に基づいて、Elapsed イベントを発生させます。 このイベントを処理して、必要な処理を実行できます。 たとえば、データベースに販売注文を継続的に転記するオンライン販売アプリケーションがあるとします。 出荷の指示をコンパイルするサービスは、各注文を個別に処理するのではなく、注文のバッチで動作します。 Timerを使用して、30 分ごとにバッチ処理を開始できます。
Important
System.Timers.Timer クラスの解像度は、システム クロックと同じです。 つまり、Interval プロパティがシステム クロックの解像度より小さい場合、Elapsed イベントはシステム クロックの解像度によって定義された間隔で発生します。 詳細については、 Interval プロパティを参照してください。
注
使用されるシステム クロックは 、GetTickCount で使用されるのと同じクロックであり、 timeBeginPeriod と timeEndPeriod で行われた変更の影響を受けません。
AutoResetが false に設定されている場合、System.Timers.Timer オブジェクトは、最初のIntervalが経過した後、Elapsed イベントを 1 回だけ発生させます。
Intervalによって定義された間隔でElapsed イベントを定期的に発生させ続けるために、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()
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()
SynchronizingObject プロパティがnull場合、Elapsed イベントはThreadPool スレッドで発生します。
Elapsed イベントの処理がIntervalよりも長く続く場合は、別のThreadPool スレッドでイベントが再度発生する可能性があります。 この状況では、イベント ハンドラーを再入する必要があります。
注
イベント処理メソッドは、別のスレッドが Stop メソッドを呼び出すか、 Enabled プロパティを false に設定すると同時に、1 つのスレッドで実行される場合があります。 これにより、タイマーの停止後に Elapsed イベントが発生する可能性があります。
Stop メソッドのコード例は、この競合状態を回避する 1 つの方法を示しています。
SynchronizingObjectがnullされていない場合でも、Elapsedイベントは、DisposeメソッドまたはStop メソッドが呼び出された後、またはEnabled プロパティがfalseに設定された後に発生する可能性があります。これは、Elapsed イベントを発生させるシグナルがスレッド プール スレッドで実行するために常にキューに入れられます。 この競合状態を解決する 1 つの方法は、後続のイベントを無視するように Elapsed イベントのイベント ハンドラーに指示するフラグを設定することです。
フォームやコントロールなどのユーザー インターフェイス要素で System.Timers.Timer クラスを使用する場合は、そのユーザー インターフェイス要素にタイマーを配置せずに、 Timer を含むフォームまたはコントロールを SynchronizingObject プロパティに割り当てて、イベントがユーザー インターフェイス スレッドにマーシャリングされるようにします。
Timerのインスタンスの既定のプロパティ値の一覧については、Timer コンストラクターを参照してください。
ヒント
.NET には Timer という名前の 4 つのクラスが含まれており、それぞれに異なる機能が用意されています。
- 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) | |
| Timer(TimeSpan) |
プロパティ
| 名前 | 説明 |
|---|---|
| AutoReset |
Timerで Elapsed イベントを 1 回だけ発生させる ( |
| 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() |
Stringの名前 (存在する場合) を含むComponentを返します。 このメソッドはオーバーライドしないでください。 (継承元 Component) |
イベント
| 名前 | 説明 |
|---|---|
| Disposed |
コンポーネントが Dispose() メソッドの呼び出しによって破棄されるときに発生します。 (継承元 Component) |
| Elapsed |
間隔が経過したときに発生します。 |
適用対象
スレッド セーフ
この型のパブリック static メンバーはスレッド セーフです。 インスタンス メンバーがスレッド セーフであるとは限りません。