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

タイマー【timer】

読み方:たいまー

タイムスイッチのこと。「—を七時セットする

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

競技などの計時係。

セルフタイマー」の略。


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 Enabledtrue設定すると、Elapsed イベントの発生開始します
パブリック メソッド Stop Enabledfalse設定すると、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 Enabledtrue設定すると、Elapsed イベントの発生開始します
パブリック メソッド Stop Enabledfalse設定すると、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)』 (2023/11/25 06:12 UTC 版)

タイマー: timer)は、「時間を測る」という意味を持つ動詞time動作主名詞英語版化した英単語で、以下のような意味を持つ。




「タイマー」の続きの解説一覧

TIMER

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

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

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

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

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


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

辞書ショートカット

すべての辞書の索引

「timer」の関連用語

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

   

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



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

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

©2024 GRAS Group, Inc.RSS