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
継承
属性
実装

次の例では、デリゲートと StatusChecker 同じシグネチャを CheckStatus 持つメソッドを含むクラスを TimerCallback 定義します。 メソッドのCheckStatus引数はstateAutoResetEventアプリケーション スレッドとコールバック デリゲートを実行するスレッド プール スレッドの同期に使用されるオブジェクトです。 クラスには、次の 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.DispatcherTimerは、キューに Dispatcher 統合されたタイマーです。 このタイマーは、指定された時間間隔で指定された優先度で処理されます。

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

注意

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

注意

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

タイマーが不要になったら、 メソッドを 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)

非同期の破棄可能から返されるタスク上での待機がどのように実行されるかを構成します。

適用対象

スレッド セーフ

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

こちらもご覧ください