Timer クラス
アセンブリ: mscorlib (mscorlib.dll 内)
構文
<ComVisibleAttribute(True)> _ Public NotInheritable Class Timer Inherits MarshalByRefObject Implements IDisposable
メモ |
---|
このクラスに適用される HostProtectionAttribute 属性の Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的には、アイコンをダブルクリック、コマンドを入力、またはブラウザに URL を入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラスのトピックまたは「SQL Server プログラミングとホスト保護属性」を参照してください。 |
TimerCallback デリゲートを使用して、Timer で実行するメソッドを指定します。タイマ デリゲートは、タイマの構築時に指定され、変更することはできません。このメソッドは、タイマを作成したスレッドで実行されず、システムが提供する ThreadPool スレッドで実行されます。
タイマを作成するときは、メソッドを最初に実行するまでの待機時間 (期限) と、その後の実行ごとに待機する時間 (期間) を指定できます。Change メソッドを使用して、これらの値を変更したり、タイマを無効にしたりできます。
メモ |
---|
Timer を使用している間は、このクラスへの参照を保持しておく必要があります。他のマネージ オブジェクトと同様、まったく参照されていない場合、Timer はガベージ コレクションの対象となります。Timer がアクティブであっても、ガベージ コレクションの対象から除外されることはありません。 |
タイマが不要になった場合は、Dispose メソッドを使用して、そのタイマが保持しているリソースを解放します。タイマが破棄されたときにシグナルを受信するには、WaitHandle を受け取る Dispose(WaitHandle) メソッド オーバーロードを使用します。WaitHandle は、タイマが破棄されると通知されます。
タイマによって実行されるコールバック メソッドは、ThreadPool スレッドで呼び出されるため、再入可能である必要があります。タイマ間隔がコールバックの実行に必要な時間よりも小さい場合、または、スレッド プール スレッドがすべて使用中でコールバックが複数回キューに置かれる場合は、コールバックを 2 つのスレッド プール スレッドで同時に実行できます。
Imports Microsoft.VisualBasic Imports System Imports System.Threading Public Class TimerExample <MTAThread> _ Shared Sub Main() Dim autoEvent As New AutoResetEvent(False) Dim statusChecker As New StatusChecker(10) ' Create the delegate that invokes methods for the timer. Dim timerDelegate As TimerCallback = _ AddressOf statusChecker.CheckStatus ' Create a timer that signals the delegate to invoke ' CheckStatus after one second, and every 1/4 second ' thereafter. Console.WriteLine("{0} Creating timer." & vbCrLf, _ DateTime.Now.ToString("h:mm:ss.fff")) Dim stateTimer As Timer = _ New Timer(timerDelegate, autoEvent, 1000, 250) ' When autoEvent signals, change the period to every ' 1/2 second. autoEvent.WaitOne(5000, False) stateTimer.Change(0, 500) Console.WriteLine(vbCrLf & "Changing period." & vbCrLf) ' When autoEvent signals the second time, dispose of ' the timer. autoEvent.WaitOne(5000, False) stateTimer.Dispose() Console.WriteLine(vbCrLf & "Destroying timer.") End Sub End Class Public Class StatusChecker Dim invokeCount, maxCount As Integer Sub New(count As Integer) invokeCount = 0 maxCount = count End Sub ' This method is called by the timer delegate. Sub CheckStatus(stateInfo As Object) Dim autoEvent As AutoResetEvent = _ DirectCast(stateInfo, AutoResetEvent) invokeCount += 1 Console.WriteLine("{0} Checking status {1,2}.", _ DateTime.Now.ToString("h:mm:ss.fff"), _ invokeCount.ToString()) If invokeCount = maxCount Then ' Reset the counter and signal to stop the timer. invokeCount = 0 autoEvent.Set() End If End Sub End Class
using System; using System.Threading; class TimerExample { static void Main() { AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(10); // Create the delegate that invokes methods for the timer. TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); // Create a timer that signals the delegate to invoke // CheckStatus after one second, and every 1/4 second // thereafter. Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); // When autoEvent signals, change the period to every // 1/2 second. autoEvent.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of // the timer. autoEvent.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); } } class StatusChecker { int invokeCount, maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString()); if(invokeCount == maxCount) { // Reset the counter and signal Main. invokeCount = 0; autoEvent.Set(); } } }
using namespace System; using namespace System::Threading; ref class StatusChecker { private: int invokeCount; int maxCount; public: StatusChecker( int count ) : invokeCount( 0 ), maxCount( count ) {} // This method is called by the timer delegate. void CheckStatus( Object^ stateInfo ) { AutoResetEvent^ autoEvent = dynamic_cast<AutoResetEvent^>(stateInfo); Console::WriteLine( "{0} Checking status {1,2}.", DateTime::Now.ToString( "h:mm:ss.fff" ), (++invokeCount).ToString() ); if ( invokeCount == maxCount ) { // Reset the counter and signal main. invokeCount = 0; autoEvent->Set(); } } }; int main() { AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false ); StatusChecker^ statusChecker = gcnew StatusChecker( 10 ); // Create the delegate that invokes methods for the timer. TimerCallback^ timerDelegate = gcnew TimerCallback( statusChecker, &StatusChecker::CheckStatus ); // Create a timer that signals the delegate to invoke CheckStatus // after one second, and every 1/4 second thereafter. Console::WriteLine( "{0} Creating timer.\n", DateTime::Now.ToString( "h:mm:ss.fff" ) ); Timer^ stateTimer = gcnew Timer( timerDelegate,autoEvent,1000,250 ); // When autoEvent signals, change the period to every 1/2 second. autoEvent->WaitOne( 5000, false ); stateTimer->Change( 0, 500 ); Console::WriteLine( "\nChanging period.\n" ); // When autoEvent signals the second time, dispose of the timer. autoEvent->WaitOne( 5000, false ); stateTimer->~Timer(); Console::WriteLine( "\nDestroying timer." ); }
import System.*; import System.Threading.*; import System.Threading.Thread; class TimerExample { public static void main(String[] args) { AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(10); // Create the delegate that invokes methods for the timer. TimerCallback timerDelegate = new TimerCallback( statusChecker.CheckStatus); // Create a timer that signals the delegate to invoke // CheckStatus after one second, and every 1/4 second // thereafter. Console.WriteLine("{0} Creating timer.\n", System.DateTime.get_Now().ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); // When autoEvent signals, change the period to every // 1/2 second. autoEvent.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of // the timer. autoEvent.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); } //main } //TimerExample class StatusChecker { private int invokeCount, maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } //StatusChecker // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = ((AutoResetEvent)(stateInfo)); Console.WriteLine("{0} Checking status {1,2}.", System.DateTime.get_Now().ToString("h:mm:ss.fff"), String.valueOf(++invokeCount)); if (invokeCount == maxCount) { // Reset the counter and signal Main. invokeCount = 0; autoEvent.Set(); } } //CheckStatus } //StatusChecker
System.MarshalByRefObject
System.Threading.Timer
プラットフォーム
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
Timer クラス
アセンブリ: System (system.dll 内)
構文
解説
メモ |
---|
このクラスに適用される HostProtectionAttribute 属性の Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的には、アイコンをダブルクリック、コマンドを入力、またはブラウザに URL を入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラスのトピックまたは「SQL Server プログラミングとホスト保護属性」を参照してください。 |
Timer コンポーネントはサーバー ベースのタイマで、これを使用して Elapsed イベントをアプリケーションで発生させる任意の間隔を指定できます。その後、このイベントを使用して、一定の間隔で処理を行うことができます。たとえば、1 日 24 時間、1 週間 7 日稼働する必要がある重要なサーバーがあるとします。定期的にサーバーをチェックし、システムが稼働状態であることを確認するために Timer を使用するサービスを作成できます。システムが応答しない場合は、このサービスによりサーバーが再起動されるか、または管理者に通知されます。
サーバー ベースの Timer は、マルチスレッド環境においてワーカー スレッドと共に使用するようにデザインされています。サーバー タイマはスレッド間を移動して、発生した Elapsed イベントを処理できます。このため、イベントを時間どおりに発生させるという点で、Windows のタイマより正確です。サーバー ベースのタイマの詳細については、「サーバー ベースのタイマの概説」を参照してください。
Timer コンポーネントは、Interval プロパティの値を基に Elapsed イベントを発生させます。このイベントを処理して、必要な処理を実行できます。たとえば、継続的にデータベースに売上をポストするオンラインのセールス アプリケーションがあるとします。配送の指示をコンパイルするサービスは、オーダーを個別にではなくバッチで処理します。Timer を使用すると、30 分ごとにバッチ処理を開始できます。
メモ |
---|
AutoReset が false に設定されている場合、Timer は最初の Interval が経過した後に、Elapsed イベントを 1 回だけ発生させます。Interval で Elapsed イベントを繰り返し発生させるには、AutoReset を true に設定します。 |
Elapsed イベントは、ThreadPool スレッドで発生します。Elapsed イベントの処理が Interval よりも長びくと、別の ThreadPool スレッドで同じイベントが再発生する場合があります。このため、イベント ハンドラは再入可能であることが必要です。
メモ |
---|
1 つのスレッドでイベント処理メソッドを実行している間に、別のスレッドで Stop メソッドを呼び出したり、Enabled プロパティを false に設定したりする可能性があります。これにより、タイマが停止した後に Elapsed イベントが発生する場合があります。Stop メソッドのコード例では、この競合状態を回避する方法の一例を示しています。 |
Timer を、フォームやコントロールなどのユーザー インターフェイス要素で使用する場合は、Timer を含むフォームまたはコントロールを SynchronizingObject プロパティに割り当てて、イベントがユーザー インターフェイス スレッドにマーシャリングされるようにする必要があります。
5 秒ごとに、コンソールに "Hello World!" と表示する Timer を作成する例を次に示します。
この例では、System.Timers 名前空間を使用します。
Imports System Imports System.Timers Public Class Timer1 Public Shared Sub Main() ' Normally, the timer is declared at the class level, so ' that it doesn't go out of scope when the method ends. ' In this example, the timer is needed only while Main ' is executing. However, KeepAlive must be used at the ' end of Main, to prevent the JIT compiler from allowing ' aggressive garbage collection to occur before Main ' ends. Dim aTimer As New System.Timers.Timer() ' Hook up the Elapsed event for the timer. AddHandler aTimer.Elapsed, AddressOf OnTimedEvent ' Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 2000 aTimer.Enabled = True Console.WriteLine("Press the Enter key to exit the program.") Console.ReadLine() ' Keep the timer alive until the end of Main. GC.KeepAlive(aTimer) End Sub ' Specify what you want to happen when the Elapsed event is ' raised. Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs) Console.WriteLine("Hello World!") End Sub End Class
using System; using System.Timers; public class Timer1 { public static void Main() { // Normally, the timer is declared at the class level, so // that it doesn't go out of scope when the method ends. // In this example, the timer is needed only while Main // is executing. However, KeepAlive must be used at the // end of Main, to prevent the JIT compiler from allowing // aggressive garbage collection to occur before Main // ends. System.Timers.Timer aTimer = new System.Timers.Timer(); // Hook up the Elapsed event for the timer. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 2000; aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); // Keep the timer alive until the end of Main. GC.KeepAlive(aTimer); } // Specify what you want to happen when the Elapsed event is // raised. private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("Hello World!"); } }
#using <system.dll> using namespace System; using namespace System::Timers; public ref class Timer1 { public: static void Demo() { // Normally, the timer is declared at the class level, so // that it doesn't go out of scope when the method ends. // In this example, the timer is needed only while Demo // is executing. However, KeepAlive must be used at the // end of Demo, to prevent the JIT compiler from allowing // aggressive garbage collection to occur before Demo // ends. System::Timers::Timer^ aTimer = gcnew System::Timers::Timer; // Hook up the Elapsed event for the timer. aTimer->Elapsed += gcnew ElapsedEventHandler( Timer1::OnTimedEvent ); // Set the Interval to 2 seconds (2000 milliseconds). aTimer->Interval = 2000; aTimer->Enabled = true; Console::WriteLine("Press the Enter key to exit the program."); Console::ReadLine(); // Keep the timer alive until the end of the Demo method. GC::KeepAlive(aTimer); } private: // Specify what you want to happen when the Elapsed event is // raised. static void OnTimedEvent( Object^ /*source*/, ElapsedEventArgs^ /*e*/ ) { Console::WriteLine( "Hello World!" ); } }; int main() { Timer1::Demo(); }
System.MarshalByRefObject
System.ComponentModel.Component
System.Timers.Timer
プラットフォーム
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
Timer クラス
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文
解説
Timer は、ユーザー定義の間隔でイベントを発生させるために使用されます。この Windows タイマは、UI スレッドを使用して処理を実行するシングルスレッド環境に合わせて設計されています。ユーザー コードには利用できる UI メッセージ ポンプが必要です。また、このコードは必ず同じスレッドから操作し、別のスレッドに対する呼び出しをマーシャリングする必要があります。
このタイマを使用するときは、Tick イベントを使用して、ポーリング操作を実行するか、スプラッシュ スクリーンを指定した時間だけ表示します。Enabled プロパティが true に設定され、Interval プロパティが 0 を超える場合、Tick イベントは、常に Interval プロパティの設定値に基づいた間隔で発生します。
このクラスには、タイマの間隔、開始および終了を設定するメソッドが用意されています。
メモ |
---|
Windows フォームのタイマ コンポーネントはシングルスレッドで、精度の上限は 55 ミリ秒になります。より精度の高いマルチスレッド タイマが必要な場合は、System.Timers 名前空間の Timer クラスを使用してください。 |
5 秒ごとにアラームを発生させる単純な間隔タイマを実装する例を次に示します。アラームが発生すると、MessageBox にアラームが起動した回数が表示され、タイマの実行を継続するかどうかをユーザーに問い合わせるメッセージが表示されます。
Public Class Class1 Private Shared myTimer As New System.Windows.Forms.Timer() Private Shared alarmCounter As Integer = 1 Private Shared exitFlag As Boolean = False ' This is the method to run when the timer is raised. Private Shared Sub TimerEventProcessor(myObject As Object, _ myEventArgs As EventArgs) myTimer.Stop() ' Displays a message box asking whether to continue running the timer. If MessageBox.Show("Continue running?", "Count is: " & alarmCounter, _ MessageBoxButtons.YesNo) = DialogResult.Yes Then ' Restarts the timer and increments the counter. alarmCounter += 1 myTimer.Enabled = True Else ' Stops the timer. exitFlag = True End If End Sub Public Shared Sub Main() ' Adds the event and the event handler for the method that will ' process the timer event to the timer. AddHandler myTimer.Tick, AddressOf TimerEventProcessor ' Sets the timer interval to 5 seconds. myTimer.Interval = 5000 myTimer.Start() ' Runs the timer, and raises the event. While exitFlag = False ' Processes all the events in the queue. Application.DoEvents() End While End Sub End Class
public class Class1 { static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer(); static int alarmCounter = 1; static bool exitFlag = false; // This is the method to run when the timer is raised. private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { myTimer.Stop(); // Displays a message box asking whether to continue running the timer. if(MessageBox.Show("Continue running?", "Count is: " + alarmCounter, MessageBoxButtons.YesNo) == DialogResult.Yes) { // Restarts the timer and increments the counter. alarmCounter +=1; myTimer.Enabled = true; } else { // Stops the timer. exitFlag = true; } } public static int Main() { /* Adds the event and the event handler for the method that will process the timer event to the timer. */ myTimer.Tick += new EventHandler(TimerEventProcessor); // Sets the timer interval to 5 seconds. myTimer.Interval = 5000; myTimer.Start(); // Runs the timer, and raises the event. while(exitFlag == false) { // Processes all the events in the queue. Application.DoEvents(); } return 0; } }
public ref class Class1 { private: static System::Windows::Forms::Timer^ myTimer = gcnew System::Windows::Forms::Timer; static int alarmCounter = 1; static bool exitFlag = false; // This is the method to run when the timer is raised. static void TimerEventProcessor( Object^ /*myObject*/, EventArgs^ /*myEventArgs*/ ) { myTimer->Stop(); // Displays a message box asking whether to continue running the timer. if ( MessageBox::Show( "Continue running?", String::Format( "Count is: {0}", alarmCounter ), MessageBoxButtons::YesNo ) == DialogResult::Yes ) { // Restarts the timer and increments the counter. alarmCounter += 1; myTimer->Enabled = true; } else { // Stops the timer. exitFlag = true; } } public: static void Main() { /* Adds the event and the event handler for the method that will process the timer event to the timer. */ myTimer->Tick += gcnew EventHandler( TimerEventProcessor ); // Sets the timer interval to 5 seconds. myTimer->Interval = 5000; myTimer->Start(); // Runs the timer, and raises the event. while ( exitFlag == false ) { // Processes all the events in the queue. Application::DoEvents(); } } }; int main() { Class1::Main(); }
public class Class1 { private static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer(); private static int alarmCounter = 1; private static boolean exitFlag = false; // This is the method to run when the timer is raised. private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { myTimer.Stop(); // Displays a message box asking whether to continue running the timer. if (MessageBox.Show("Continue running?", "Count is: " + alarmCounter, MessageBoxButtons.YesNo).Equals(DialogResult.Yes)) { // Restarts the timer and increments the counter. alarmCounter += 1; myTimer.set_Enabled(true); } else { // Stops the timer. exitFlag = true; } } //TimerEventProcessor public static void main(String[] args) { /* Adds the event and the event handler for the method that will process the timer event to the timer. */ myTimer.add_Tick(new EventHandler(TimerEventProcessor)); // Sets the timer interval to 5 seconds. myTimer.set_Interval(5000); myTimer.Start(); // Runs the timer, and raises the event. while (exitFlag == false) { // Processes all the events in the queue. Application.DoEvents(); } return; } //main } //Class1
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Timer
プラットフォーム
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
- Timer クラスのページへのリンク