Timer クラス

定義

指定した間隔でスレッド プール スレッドでメソッドを実行するためのメカニズムを提供します。 このクラスは継承できません。

public ref class Timer sealed : IDisposable
public ref class Timer sealed : MarshalByRefObject, IAsyncDisposable, IDisposable
public ref class Timer sealed : MarshalByRefObject, System::Threading::ITimer
public ref class Timer sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : IDisposable
public sealed class Timer : MarshalByRefObject, IAsyncDisposable, IDisposable
public sealed class Timer : MarshalByRefObject, System.Threading.ITimer
public sealed class Timer : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
    interface ITimer
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class Timer
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IAsyncDisposable, IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements ITimer
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
継承
Timer
継承
属性
実装

次の例では、TimerCallback デリゲートと同じシグネチャを持つ CheckStatus メソッドを含む StatusChecker クラスを定義します。 CheckStatus メソッドの state 引数は、アプリケーション スレッドとコールバック デリゲートを実行するスレッド プール スレッドの同期に使用される AutoResetEvent オブジェクトです。 StatusChecker クラスには、次の 2 つの状態変数も含まれています。

invokeCount コールバック メソッドが呼び出された回数を示します。

maxCount コールバック メソッドを呼び出す最大回数を決定します。

アプリケーション スレッドはタイマーを作成します。タイマーは 1 秒待ってから、250 ミリ秒ごとに CheckStatus コールバック メソッドを実行します。 その後、アプリケーション スレッドは、AutoResetEvent オブジェクトが通知されるまでブロックします。 CheckStatus コールバック メソッドは、maxCount 回実行すると、AutoResetEvent.Set メソッドを呼び出して、AutoResetEvent オブジェクトの状態を signaled に設定します。 これが初めて発生すると、アプリケーション スレッドは Change(Int32, Int32) メソッドを呼び出して、コールバック メソッドが 5 分の 1 秒ごとに実行されるようにします。 AutoResetEvent オブジェクトが通知されるまで、もう一度ブロックします。 この場合、タイマーは Dispose メソッドを呼び出すことによって破棄され、アプリケーションは終了します。

using namespace System;
using namespace System::Threading;

ref class StatusChecker
{
private:
    int invokeCount, 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:h:mm:ss.fff} Checking status {1,2}.",
                           DateTime::Now, ++invokeCount);

        if (invokeCount == maxCount) {
            // Reset the counter and signal the waiting thread.
            invokeCount  = 0;
            autoEvent->Set();
        }
    }
};

ref class TimerExample
{
public:
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        AutoResetEvent^ autoEvent = gcnew AutoResetEvent(false);

        StatusChecker^ statusChecker = gcnew StatusChecker(10);

        // Create a delegate that invokes methods for the timer.
        TimerCallback^ tcb =
           gcnew TimerCallback(statusChecker, &StatusChecker::CheckStatus);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console::WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
                           DateTime::Now);
        Timer^ stateTimer = gcnew Timer(tcb, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent->WaitOne(5000, false);
        stateTimer->Change(0, 500);
        Console::WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent->WaitOne(5000, false);
        stateTimer->~Timer();
        Console::WriteLine("\nDestroying timer.");
    }
};

int main()
{
    TimerExample::Main();
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        var autoEvent = new AutoResetEvent(false);
        
        var statusChecker = new StatusChecker(10);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", 
                          DateTime.Now);
        var stateTimer = new Timer(statusChecker.CheckStatus, 
                                   autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne();
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne();
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    private int invokeCount;
    private int  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 the waiting thread.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Use an AutoResetEvent to signal the timeout threshold in the
        ' timer callback has been reached.
        Dim autoEvent As New AutoResetEvent(False)

        Dim statusChecker As New StatusChecker(10)

        ' Create a timer that invokes CheckStatus after one second, 
        ' and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer." & vbCrLf, 
                          DateTime.Now)
        Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus, 
                                    autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne()
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)

        ' When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne()
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")
    End Sub
End Module

Public Class StatusChecker
    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' The timer callback method.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.", 
                          DateTime.Now, invokeCount)
        If invokeCount = maxCount Then
            ' Reset the counter and signal the waiting thread.
            invokeCount = 0
            autoEvent.Set()
        End If
    End Sub
End Class
' The example displays output like the following:
'       11:59:54.202 Creating timer.
'       
'       11:59:55.217 Checking status  1.
'       11:59:55.466 Checking status  2.
'       11:59:55.716 Checking status  3.
'       11:59:55.968 Checking status  4.
'       11:59:56.218 Checking status  5.
'       11:59:56.470 Checking status  6.
'       11:59:56.722 Checking status  7.
'       11:59:56.972 Checking status  8.
'       11:59:57.223 Checking status  9.
'       11:59:57.473 Checking status 10.
'       
'       Changing period to .5 seconds.
'       
'       11:59:57.474 Checking status  1.
'       11:59:57.976 Checking status  2.
'       11:59:58.476 Checking status  3.
'       11:59:58.977 Checking status  4.
'       11:59:59.477 Checking status  5.
'       11:59:59.977 Checking status  6.
'       12:00:00.478 Checking status  7.
'       12:00:00.980 Checking status  8.
'       12:00:01.481 Checking status  9.
'       12:00:01.981 Checking status 10.
'       
'       Destroying timer.

注釈

TimerCallback デリゲートを使用して、Timer を実行するメソッドを指定します。 TimerCallback デリゲートのシグネチャは次のとおりです。

void TimerCallback(Object state)
void TimerCallback(Object state)
Sub TimerCallback(state As Object)

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

先端

.NET にはいくつかのタイマー クラスが含まれており、それぞれに異なる機能が用意されています。

  • System.Timers.Timer:イベントを発生させ、一定の間隔で 1 つ以上のイベント シンクでコードを実行します。 このクラスは、マルチスレッド環境でサーバー ベースまたはサービス コンポーネントとして使用することを目的としています。ユーザー インターフェイスがなく、実行時には表示されません。
  • System.Threading.Timer。スレッド プール スレッドに対して一定の間隔で 1 つのコールバック メソッドを実行します。 コールバック メソッドは、タイマーがインスタンス化されるときに定義され、変更できません。 System.Timers.Timer クラスと同様に、このクラスは、マルチスレッド環境でサーバー ベースまたはサービス コンポーネントとして使用することを目的としています。ユーザー インターフェイスがなく、実行時には表示されません。
  • System.Windows.Forms.Timer、イベントを発生させ、一定の間隔で 1 つ以上のイベント シンクでコードを実行する Windows フォーム コンポーネントです。 コンポーネントにはユーザー インターフェイスがなく、シングルスレッド環境で使用するように設計されています。UI スレッドで実行されます。
  • System.Web.UI.Timer (.NET Framework のみ)、非同期または同期 Web ページのポストバックを一定の間隔で実行する ASP.NET コンポーネントです。
  • System.Windows.Threading.DispatcherTimerDispatcher キューに統合されるタイマーです。 このタイマーは、指定した間隔で指定された優先度で処理されます。

タイマーを作成するときに、メソッドの最初の実行までの待機時間 (期限) と、後続の実行 (期間) の間に待機する時間を指定できます。 Timer クラスの解像度はシステム クロックと同じです。 つまり、期間がシステム クロックの解像度より小さい場合、TimerCallback デリゲートは、システム クロックの解像度によって定義された間隔 (Windows 7 および Windows 8 システムでは約 15 ミリ秒) で実行されます。 Change メソッドを使用して、期限と期間を変更したり、タイマーを無効にしたりできます。

手記

Timerを使用している限り、その参照を保持する必要があります。 マネージド オブジェクトと同様に、Timer は参照がない場合にガベージ コレクションの対象となります。 Timer がまだアクティブであるという事実は、収集を妨げるものではありません。

手記

使用されるシステム クロックは、GetTickCountで使用されるのと同じクロックであり、timeBeginPeriod と timeEndPeriod変更の影響を受けません。

タイマーが不要になったら、Dispose メソッドを使用して、タイマーによって保持されているリソースを解放します。 タイマーはスレッド プール スレッドによる実行のコールバックをキューに入れるので、Dispose() メソッドのオーバーロードが呼び出された後にコールバックが発生する可能性があることに注意してください。 Dispose(WaitHandle) メソッドのオーバーロードを使用して、すべてのコールバックが完了するまで待機できます。

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

手記

System.Threading.Timer は、コールバック メソッドを使用し、スレッド プール スレッドによって提供されるシンプルで軽量なタイマーです。 ユーザー インターフェイス スレッドではコールバックが発生しないため、Windows フォームでの使用はお勧めしません。 System.Windows.Forms.Timer は、Windows フォームで使用する方が適しています。 サーバー ベースのタイマー機能の場合は、イベントを発生させ、その他の機能を備える System.Timers.Timerの使用を検討できます。

コンストラクター

Timer(TimerCallback)

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

Timer(TimerCallback, Object, Int32, Int32)

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

Timer(TimerCallback, Object, Int64, Int64)

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

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

TimeSpan 値を使用して時間間隔を測定し、Timer クラスの新しいインスタンスを初期化します。

Timer(TimerCallback, Object, UInt32, UInt32)

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

プロパティ

ActiveCount

現在アクティブなタイマーの数を取得します。 アクティブなタイマーは、将来のある時点でティックするように登録され、まだ取り消されていません。

メソッド

Change(Int32, Int32)

タイマーのメソッド呼び出しの開始時刻と間隔を変更します。32 ビット符号付き整数を使用して時間間隔を測定します。

Change(Int64, Int64)

64 ビット符号付き整数を使用して時間間隔を測定し、タイマーのメソッド呼び出しの開始時刻と間隔を変更します。

Change(TimeSpan, TimeSpan)

TimeSpan 値を使用して時間間隔を測定し、タイマーのメソッド呼び出しの開始時刻と間隔を変更します。

Change(UInt32, UInt32)

32 ビット符号なし整数を使用して時間間隔を測定し、タイマーのメソッド呼び出しの開始時刻と間隔を変更します。

CreateObjRef(Type)

リモート オブジェクトとの通信に使用されるプロキシの生成に必要なすべての関連情報を含むオブジェクトを作成します。

(継承元 MarshalByRefObject)
Dispose()

Timerの現在のインスタンスで使用されているすべてのリソースを解放します。

Dispose(WaitHandle)

Timer の現在のインスタンスで使用されているすべてのリソースを解放し、タイマーが破棄されたときに通知します。

DisposeAsync()

Timerの現在のインスタンスで使用されているすべてのリソースを解放します。

Equals(Object)

指定したオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Finalize()

オブジェクトがガベージ コレクションによって解放される前に、リソースを解放し、その他のクリーンアップ操作を実行できるようにします。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する現在の有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
InitializeLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。

(継承元 MarshalByRefObject)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

拡張メソッド

ConfigureAwait(IAsyncDisposable, Boolean)

非同期破棄から返されるタスクの待機を実行する方法を構成します。

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください