Timer コンストラクタとは? わかりやすく解説

Timer コンストラクタ (IContainer)

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

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

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

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 内)
構文構文

例外例外
例外種類条件

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 内)
構文構文

例外例外
例外種類条件

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 _
)
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
アセンブリ: 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.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

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



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

辞書ショートカット

すべての辞書の索引

「Timer コンストラクタ」の関連用語

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

   

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



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

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

©2025 GRAS Group, Inc.RSS