timerとは? わかりやすく解説

タイマー【timer】

読み方:たいまー

1 タイムスイッチのこと。「―を七時にセットする」

2 ストップウオッチのこと。

3 競技などの計時係。

4 「セルフタイマー」の略。


Timer イベント


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) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer コンストラクタ ()

Timer クラスの新しいインスタンスを初期化し、すべてのプロパティを初期値に設定します。

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

解説解説
使用例使用例

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();
}

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Timer クラス
Timer メンバ
System.Timers 名前空間
AutoReset
Enabled
Interval
SynchronizingObject

Timer コンストラクタ ()

Timer クラスの新しいインスタンスを初期化します。

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

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

Timer コンストラクタ (IContainer)

Timer クラスの新しいインスタンスと、指定したコンテナを初期化します。

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

Public Sub New ( _
    container As IContainer _
)
public Timer (
    IContainer container
)
public:
Timer (
    IContainer^ container
)
public Timer (
    IContainer container
)
public function Timer (
    container : IContainer
)

パラメータ

container

タイマのコンテナを表す IContainer。

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

Timer コンストラクタ


Timer コンストラクタ (TimerCallback, Object, UInt32, UInt32)

時間間隔を計るために 32 ビット符号なし整数を使用して、Timer クラスの新しいインスタンスを初期化します。

このコンストラクタは、CLS に準拠していません。  

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

<CLSCompliantAttribute(False)> _
Public Sub New ( _
    callback As TimerCallback, _
    state As Object, _
    dueTime As UInteger, _
    period As UInteger _
)
Dim callback As TimerCallback
Dim state As Object
Dim dueTime As UInteger
Dim period As UInteger

Dim instance As New Timer(callback,
 state, dueTime, period)
[CLSCompliantAttribute(false)] 
public Timer (
    TimerCallback callback,
    Object state,
    uint dueTime,
    uint period
)
[CLSCompliantAttribute(false)] 
public:
Timer (
    TimerCallback^ callback, 
    Object^ state, 
    unsigned int dueTime, 
    unsigned int period
)
/** @attribute CLSCompliantAttribute(false) */ 
public Timer (
    TimerCallback callback, 
    Object state, 
    UInt32 dueTime, 
    UInt32 period
)
CLSCompliantAttribute(false) 
public function Timer (
    callback : TimerCallback, 
    state : Object, 
    dueTime : uint, 
    period : uint
)

パラメータ

callback

実行するメソッドを表す TimerCallback デリゲート。

state

コールバック メソッドで使用される情報を格納するオブジェクト。または null 参照 (Visual Basic では Nothing)。

dueTime

callback が呼び出される前の遅延時間 (ミリ秒単位) です。タイマが開始されないようにするには Timeout.Infinite を指定します。0 を指定すると、タイマはすぐに開始されます。

period

callback が呼び出される時間間隔 (ミリ秒単位) です。周期的なシグナル通知を無効にするには Timeout.Infinite を指定します。

例外例外
例外の種類条件

ArgumentOutOfRangeException

dueTime パラメータまたは period パラメータが負の値であり、Infinite と等しくありません。

ArgumentNullException

callback パラメータが null 参照 (Visual Basic では Nothing) です。

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

Timer コンストラクタ (TimerCallback, Object, Int32, Int32)

時間間隔を指定するために 32 ビット符号付き整数を使用して、Timer クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    callback As TimerCallback, _
    state As Object, _
    dueTime As Integer, _
    period As Integer _
)
Dim callback As TimerCallback
Dim state As Object
Dim dueTime As Integer
Dim period As Integer

Dim instance As New Timer(callback,
 state, dueTime, period)
public Timer (
    TimerCallback callback,
    Object state,
    int dueTime,
    int period
)
public:
Timer (
    TimerCallback^ callback, 
    Object^ state, 
    int dueTime, 
    int period
)
public Timer (
    TimerCallback callback, 
    Object state, 
    int dueTime, 
    int period
)
public function Timer (
    callback : TimerCallback, 
    state : Object, 
    dueTime : int, 
    period : int
)

パラメータ

callback

実行するメソッドを表す TimerCallback デリゲート。

state

コールバック メソッドで使用される情報を格納するオブジェクト。または null 参照 (Visual Basic では Nothing)。

dueTime

callback が呼び出される前の遅延時間 (ミリ秒単位) です。タイマが開始されないようにするには Timeout.Infinite を指定します。0 を指定すると、タイマはすぐに開始されます。

period

callback が呼び出される時間間隔 (ミリ秒単位) です。周期的なシグナル通知を無効にするには Timeout.Infinite を指定します。

例外例外
例外の種類条件

ArgumentOutOfRangeException

dueTime パラメータまたは period パラメータが負の値であり、Infinite と等しくありません。

ArgumentNullException

callback パラメータが null 参照 (Visual Basic では Nothing) です。

解説解説
使用例使用例

TimerCallback デリゲートを作成し、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
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer コンストラクタ (TimerCallback, Object, Int64, Int64)

時間間隔を計るために 64 ビット符号付き整数を使用して、Timer クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    callback As TimerCallback, _
    state As Object, _
    dueTime As Long, _
    period As Long _
)
Dim callback As TimerCallback
Dim state As Object
Dim dueTime As Long
Dim period As Long

Dim instance As New Timer(callback,
 state, dueTime, period)
public Timer (
    TimerCallback callback,
    Object state,
    long dueTime,
    long period
)
public:
Timer (
    TimerCallback^ callback, 
    Object^ state, 
    long long dueTime, 
    long long period
)
public Timer (
    TimerCallback callback, 
    Object state, 
    long dueTime, 
    long period
)
public function Timer (
    callback : TimerCallback, 
    state : Object, 
    dueTime : long, 
    period : long
)

パラメータ

callback

実行するメソッドを表す TimerCallback デリゲート。

state

コールバック メソッドで使用される情報を格納するオブジェクト。または null 参照 (Visual Basic では Nothing)。

dueTime

callback が呼び出される前の遅延時間 (ミリ秒単位) です。タイマが開始されないようにするには Timeout.Infinite を指定します。0 を指定すると、タイマはすぐに開始されます。

period

callback が呼び出される時間間隔 (ミリ秒単位) です。周期的なシグナル通知を無効にするには Timeout.Infinite を指定します。

例外例外
例外の種類条件

ArgumentOutOfRangeException

dueTime パラメータまたは period パラメータが負の値であり、Infinite と等しくありません。

NotSupportedException

dueTime パラメータまたは period パラメータが 4294967294 より大きい値です。

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

Timer コンストラクタ (TimerCallback, Object, TimeSpan, TimeSpan)

時間間隔を計るために TimeSpan 値を使用して、Timer クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    callback As TimerCallback, _
    state As Object, _
    dueTime As TimeSpan, _
    period As TimeSpan _
)
Dim callback As TimerCallback
Dim state As Object
Dim dueTime As TimeSpan
Dim period As TimeSpan

Dim instance As New Timer(callback,
 state, dueTime, period)
public Timer (
    TimerCallback callback,
    Object state,
    TimeSpan dueTime,
    TimeSpan period
)
public:
Timer (
    TimerCallback^ callback, 
    Object^ state, 
    TimeSpan dueTime, 
    TimeSpan period
)
public Timer (
    TimerCallback callback, 
    Object state, 
    TimeSpan dueTime, 
    TimeSpan period
)
public function Timer (
    callback : TimerCallback, 
    state : Object, 
    dueTime : TimeSpan, 
    period : TimeSpan
)

パラメータ

callback

実行するメソッドを表す TimerCallback デリゲート。

state

コールバック メソッドで使用される情報を格納するオブジェクト。または null 参照 (Visual Basic では Nothing)。

dueTime

callback パラメータがそのメソッドを呼び出す前に遅延する時間を表す TimeSpan。-1 ミリ秒を指定して、タイマが開始されないようにします。0 を指定して、タイマをすぐに開始します。

period

callback によって参照されるメソッドの呼び出し時間間隔。-1 ミリ秒を指定して、周期的なシグナル通知を無効にします。

例外例外
例外の種類条件

ArgumentOutOfRangeException

dueTime または period の値のミリ秒数が負の値で Infinite と等しくないか、MaxValue より大きい値です。

ArgumentNullException

callback パラメータが null 参照 (Visual Basic では Nothing) です。

解説解説
使用例使用例

TimerCallback デリゲートを作成し、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

        Dim delayTime As New
 TimeSpan(0, 0, 1)
        Dim intervalTime As New
 TimeSpan(0, 0, 0, 0, 250)

        ' 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, delayTime, intervalTime)

        ' When autoEvent signals, change the period to every 
        ' 1/2 second.
        autoEvent.WaitOne(5000, False)
        stateTimer.Change( _
            new TimeSpan(0), intervalTime.Add(intervalTime))
        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);

        TimeSpan delayTime = new TimeSpan(0, 0, 1);
        TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);

        // 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, delayTime, intervalTime);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(new TimeSpan(0), 
            intervalTime + intervalTime);
        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
 );
   TimeSpan delayTime = TimeSpan(0,0,1);
   TimeSpan intervalTime = TimeSpan(0,0,0,0,250);
   
   // 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,delayTime,intervalTime
 );
   
   // When autoEvent signals, change the period to every 1/2 second.
   autoEvent->WaitOne( 5000, false );
   stateTimer->Change( TimeSpan(0), intervalTime + intervalTime );
   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);
        TimeSpan delayTime = new TimeSpan(0, 0, 1);
        TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);

        // 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,
 
            delayTime, intervalTime);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(new TimeSpan(0), intervalTime.Add(intervalTime));
        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
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer コンストラクタ (Double)

Timer クラスの新しいインスタンスを初期化し、Interval プロパティを指定した間隔に設定します。

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

例外例外
例外の種類条件

ArgumentException

interval パラメータの値が 0 未満です。

使用例使用例

10 秒経過すると、コンソールに "Hello World!" と表示する Timer を作成する例を次に示します。

この例では、System.Timers 名前空間を使用します。

' From command line, compile with /r:System.dll
Imports System
Imports System.Timers

Public Class Timer2
    
    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.
        '
        ' Create a timer with a ten second interval.
        Dim aTimer As New
 System.Timers.Timer(10000)

        ' Hook up the event handler for the Elapsed event.
        AddHandler aTimer.Elapsed, AddressOf
 OnTimedEvent

        ' Only raise the event the first time Interval elapses.
        aTimer.AutoReset = False
        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
// From command line, compile with /r:System.dll
using System;
using System.Timers;

public class Timer2
{
    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.
        //
        // Create a timer with a ten second interval.
        System.Timers.Timer aTimer = new System.Timers.Timer(10000);

        // Hook up the event handler for the Elapsed event.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Only raise the event the first time Interval elapses.
        aTimer.AutoReset = false;
        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 Timer2
{
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 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.
      //
      // Create a new Timer with Interval set to 10 seconds.
      System::Timers::Timer^ aTimer = gcnew System::Timers::Timer( 10000 );

      // Hook up the event handler for the Elapsed event.
      aTimer->Elapsed += gcnew ElapsedEventHandler( OnTimedEvent );
      
      // Only raise the event the first time Interval elapses.
      aTimer->AutoReset = false;
      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()
{
   Timer2::Main();
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer コンストラクタ (TimerCallback)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

状態オブジェクトとして新しく作成した Timer を使用して、無制限の期間および無制限の期限を指定して Timer クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    callback As TimerCallback _
)
Dim callback As TimerCallback

Dim instance As New Timer(callback)
public Timer (
    TimerCallback callback
)
public:
Timer (
    TimerCallback^ callback
)
public Timer (
    TimerCallback callback
)
public function Timer (
    callback : TimerCallback
)

パラメータ

callback

実行するメソッドを表す TimerCallback デリゲート。

解説解説
使用例使用例

タイマ自体を状態オブジェクトとして使用して新しいタイマを作成するコード例を次に示します。Change メソッドは、タイマを開始するために使用します。タイマのコールバックが発生すると、状態オブジェクトを使用してタイマがオフにされます。

Imports System
Imports System.Threading

Public Class Example
    Public Shared Sub Main()
        ' Create an instance of the Example class, and start two
        ' timers.
        Dim ex As New Example()
        ex.StartTimer(2000)
        ex.StartTimer(1000)

        Console.WriteLine("Press Enter to end the program.")
        Console.ReadLine()
    End Sub

    Public Sub StartTimer(ByVal
 dueTime As Integer)
        Dim t As New Timer(AddressOf
 TimerProc)
        t.Change(dueTime, 0)
    End Sub

    Private Sub TimerProc(ByVal
 state As Object)
        ' The state object is the Timer object.
        Dim t As Timer = CType(state, Timer)
        t.Dispose()
        Console.WriteLine("The timer callback executes.")
    End Sub
End Class
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create an instance of the Example class, and start two
        // timers.
        Example ex = new Example();
        ex.StartTimer(2000);
        ex.StartTimer(1000);

        Console.WriteLine("Press Enter to end the program.");
        Console.ReadLine();
    }

    public void StartTimer(int
 dueTime)
    {
        Timer t = new Timer(new TimerCallback(TimerProc));
        t.Change(dueTime, 0);
    }

    private void TimerProc(object state)
    {
        // The state object is the Timer object.
        Timer t = (Timer) state;
        t.Dispose();
        Console.WriteLine("The timer callback executes.");
    }
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer コンストラクタ


Timer コンストラクタ


Timer プロパティ


パブリック プロパティパブリック プロパティ

プロテクト プロパティプロテクト プロパティ
参照参照

関連項目

Timer クラス
System.Timers 名前空間
AutoReset
Interval
Elapsed
Timer

その他の技術情報

サーバー ベースのタイマの概説

Timer プロパティ


Timer メソッド


パブリック メソッドパブリック メソッド

  名前 説明
パブリック メソッド Change オーバーロードされます。 タイマの開始時刻とメソッドの呼び出しの間隔を変更します。
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。 Timer の現在のインスタンスによって使用されているすべてのリソースを解放します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
参照参照

関連項目

Timer クラス
System.Threading 名前空間
TimerCallback

その他の技術情報

タイマ
マネージ スレッド プール

Timer メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド BeginInit フォームまたは別のコンポーネントで使用する Timer の実行時の初期化を開始します。
パブリック メソッド Close Timer によって使用されているリソースを解放します。
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。 現在の Timer によって使用されているすべてのリソースを解放します。
パブリック メソッド EndInit フォームまたは別のコンポーネントで使用する Timer の実行時の初期化を終了します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Start Enabled を true に設定すると、Elapsed イベントの発生を開始します。
パブリック メソッド Stop Enabled を false に設定すると、Elapsed イベントの発生を停止します。
パブリック メソッド ToString  Component の名前を格納している String を返します (存在する場合)。このメソッドはオーバーライドできません。 ( Component から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Timer クラス
System.Timers 名前空間
AutoReset
Interval
Elapsed
Timer

その他の技術情報

サーバー ベースのタイマの概説

Timer メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。  
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Start タイマを起動します。
パブリック メソッド Stop タイマを停止します。
パブリック メソッド ToString オーバーライドされます。 Timer を表す文字列を返します。
プロテクト メソッドプロテクト メソッド
参照参照

Timer メンバ

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

Timer データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック メソッドパブリック メソッド
  名前 説明
パブリック メソッド Change オーバーロードされます。 タイマの開始時刻とメソッドの呼び出しの間隔を変更します。
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。 Timer の現在のインスタンスによって使用されているすべてのリソースを解放します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
参照参照

関連項目

Timer クラス
System.Threading 名前空間
TimerCallback

その他の技術情報

タイマ
マネージ スレッド プール

Timer メンバ

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

Timer データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
プロテクト プロパティプロテクト プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド BeginInit フォームまたは別のコンポーネントで使用する Timer の実行時の初期化を開始します。
パブリック メソッド Close Timer によって使用されているリソースを解放します。
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。 現在の Timer によって使用されているすべてのリソースを解放します。
パブリック メソッド EndInit フォームまたは別のコンポーネントで使用する Timer の実行時の初期化を終了します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド Start Enabled を true に設定すると、Elapsed イベントの発生を開始します。
パブリック メソッド Stop Enabled を false に設定すると、Elapsed イベントの発生を停止します。
パブリック メソッド ToString  Component の名前を格納している String を返します (存在する場合)。このメソッドはオーバーライドできません。 (Component から継承されます。)
プロテクト メソッドプロテクト メソッド
パブリック イベントパブリック イベント
参照参照

関連項目

Timer クラス
System.Timers 名前空間
AutoReset
Interval
Elapsed
Timer

その他の技術情報

サーバー ベースのタイマの概説

Timer メンバ

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

Timer データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
プロテクト プロパティプロテクト プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。  
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド Start タイマを起動します。
パブリック メソッド Stop タイマを停止します。
パブリック メソッド ToString オーバーライドされます。 Timer を表す文字列を返します。
プロテクト メソッドプロテクト メソッド
パブリック イベントパブリック イベント
参照参照

TIMER

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2021/08/03 08:45 UTC 版)

「Hellsinker.」の記事における「TIMER」の解説

ステージ開始からの経過時間(単位は秒)を表す数値。

※この「TIMER」の解説は、「Hellsinker.」の解説の一部です。
「TIMER」を含む「Hellsinker.」の記事については、「Hellsinker.」の概要を参照ください。

ウィキペディア小見出し辞書の「timer」の項目はプログラムで機械的に意味や本文を生成しているため、不適切な項目が含まれていることもあります。ご了承くださいませ。 お問い合わせ。


英和和英テキスト翻訳

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

辞書ショートカット

すべての辞書の索引

「timer」の関連用語

timerのお隣キーワード
検索ランキング

   

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



timerのページの著作権

   
デジタル大辞泉デジタル大辞泉
(C)Shogakukan Inc.
株式会社 小学館
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.
ウィキペディアウィキペディア
Text is available under GNU Free Documentation License (GFDL).
Weblio辞書に掲載されている「ウィキペディア小見出し辞書」の記事は、WikipediaのHellsinker. (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。

©2026 GRAS Group, Inc.RSS