Timer クラスとは? わかりやすく解説

Timer クラス

指定した間隔メソッド実行するための機構提供します。このクラス継承できません。

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public NotInheritable Class
 Timer
    Inherits MarshalByRefObject
    Implements IDisposable
[ComVisibleAttribute(true)] 
public sealed class Timer : MarshalByRefObject,
 IDisposable
[ComVisibleAttribute(true)] 
public ref class Timer sealed : public
 MarshalByRefObject, IDisposable
/** @attribute ComVisibleAttribute(true) */ 
public final class Timer extends MarshalByRefObject
 implements IDisposable
ComVisibleAttribute(true) 
public final class Timer extends
 MarshalByRefObject implements IDisposable
解説解説
メモメモ

このクラス適用される HostProtectionAttribute 属性Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的にはアイコンダブルクリックコマンド入力、またはブラウザURL入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラストピックまたは「SQL Server プログラミングホスト保護属性」を参照してください

TimerCallback デリゲート使用してTimer実行するメソッド指定しますタイマ デリゲートは、タイマ構築時に指定され変更することはできません。このメソッドは、タイマ作成したスレッド実行されず、システム提供する ThreadPool スレッド実行されます。

タイマ作成するときは、メソッド最初に実行するまでの待機時間 (期限) と、その後実行ごとに待機する時間 (期間) を指定できますChange メソッド使用して、これらの値を変更したり、タイマ無効にしたりできます

タイマ不要になった場合は、Dispose メソッド使用して、そのタイマ保持しているリソース解放します。タイマ破棄されたときにシグナル受信するには、WaitHandle を受け取Dispose(WaitHandle) メソッド オーバーロード使用しますWaitHandle は、タイマ破棄される通知されます。

タイマによって実行されるコールバック メソッドは、ThreadPool スレッド呼び出されるため、再入可能である必要がありますタイマ間隔コールバック実行必要な時間よりも小さ場合、または、スレッド プール スレッドがすべて使用中コールバック複数キュー置かれる場合は、コールバック2 つスレッド プール スレッド同時に実行できます

使用例使用例

Timer クラス機能次の例で示します

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.Object
   System.MarshalByRefObject
    System.Threading.Timer
スレッド セーフスレッド セーフ

この型は、マルチスレッド操作に対して安全です。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer クラス

アプリケーション定期的にイベント生成します

名前空間: System.Timers
アセンブリ: System (system.dll 内)
構文構文

Public Class Timer
    Inherits Component
    Implements ISupportInitialize
public class Timer : Component, ISupportInitialize
public ref class Timer : public
 Component, ISupportInitialize
public class Timer extends Component implements
 ISupportInitialize
public class Timer extends
 Component implements ISupportInitialize
解説解説
メモメモ

このクラス適用される HostProtectionAttribute 属性Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的にはアイコンダブルクリックコマンド入力、またはブラウザURL入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラストピックまたは「SQL Server プログラミングホスト保護属性」を参照してください

Timer コンポーネントサーバー ベースタイマで、これを使用して Elapsed イベントアプリケーション発生させる任意の間隔指定できますその後、このイベント使用して一定の間隔で処理を行うことができます。たとえば、1 日 24 時間1 週間 7 日稼働する必要がある重要なサーバーがあるとします定期的にサーバーチェックしシステム稼働状態であることを確認するために Timer使用するサービス作成できますシステム応答しない場合は、このサービスによりサーバー再起動されるか、または管理者通知されます。

サーバー ベースTimer は、マルチスレッド環境においてワーカー スレッドと共に使用するようにデザインされています。サーバー タイマスレッド間を移動して発生した Elapsed イベントを処理できますこのためイベント時間どおりに発生させるという点で、Windowsタイマより正確です。サーバー ベースタイマ詳細については、「サーバー ベースタイマ概説」を参照してください

Timer コンポーネントは、Interval プロパティの値を基に Elapsed イベント発生させます。このイベント処理して必要な処理を実行できます。たとえば、継続的にデータベース売上ポストするオンラインセールス アプリケーションがあるとします配送指示コンパイルするサービスは、オーダー個別ではなくバッチ処理しますTimer使用すると、30 分ごとにバッチ処理開始できます

Elapsed イベントは、ThreadPool スレッド発生しますElapsed イベントの処理が Interval よりも長びくと、別の ThreadPool スレッドで同じイベント再発生す場合ありますこのためイベント ハンドラ再入可能であることが必要です。

Timer を、フォームコントロールなどのユーザー インターフェイス要素使用する場合は、Timer を含むフォームまたはコントロールを SynchronizingObject プロパティ割り当ててイベントユーザー インターフェイス スレッドマーシャリングされるようにする必要があります

実行時には Timer参照できません。

Timerインスタンス初期プロパティ値の一覧については、Timer コンストラクタトピック参照してください

使用例使用例

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.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.Timers.Timer
スレッド セーフスレッド セーフ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer クラス

ユーザー定義の間隔イベント発生させるタイマ実装ます。このタイマは、Windows フォーム アプリケーション使用できるように最適化されていて、ウィンドウ使用する必要があります

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

解説解説
使用例使用例

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.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.Windows.Forms.Timer
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Timer クラス」の関連用語

Timer クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Timer クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS