Tips26

Last-modified: 2011-08-29 (月) 15:28:44

Timer 時間差、一定時間毎に実行

  • カテゴリー: スクリプト
  • 重要性: 普通
  • 投稿日: 2005-08-14 (日) 01:32:22

時間差をつけたいときや、一定時間毎に実行したい時に使うのがTimerクラスです。スクリプトを眺めているとしばしば見かけるInternalTimerはTimerのサブクラスです。

時間差

一番使いやすいものを紹介します。

public static Timer DelayCall( TimeSpan delay, TimerStateCallback callback, object state )

delay
実行するまでの時間
callback
実行されるメソッド
state
callbackの引数

サンプルはTips18と同じですが、Scripts\Items\Skill Items\Magical\Potions\Heal Potions\BaseHealPotion.csの動作で説明します。

public override void Drink( Mobile from )
{
if ( from.Hits < from.HitsMax )
{
if ( from.Poisoned || MortalStrike.IsWounded( from ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x22, 1005000 ); // You can not heal yourself in your current state.
}
else
{
if ( from.BeginAction( typeof( BaseHealPotion ) ) )
{
DoHeal( from );

BasePotion.PlayDrinkEffect( from );

this.Delete();

Timer.DelayCall( TimeSpan.FromSeconds( Delay ), new TimerStateCallback( ReleaseHealLock ), from );
}
else
{
from.LocalOverheadMessage( MessageType.Regular, 0x22, 500235 ); // You must wait 10 seconds before using another healing potion.
}
}
}
else
{
from.SendLocalizedMessage( 1049547 ); // You decide against drinking this potion, as you are already at full health.
}
}

private static void ReleaseHealLock( object state )
{
((Mobile)state).EndAction( typeof( BaseHealPotion ) );
}

Timer.DelayCall( TimeSpan.FromSeconds( Delay ), new TimerStateCallback( ReleaseHealLock ), from );

TimeSpan.FromSecondsはdouble型のDelayを秒でTimeSpan型に変換します。 10.0の場合10秒です。 new TimerStateCallback()は、この使い方をするときのお決まりの書き方だと思ってください。new TimerCallBack()という使い方もありますが、その場合引数の指定が出来ません。 fromは ReleaseHealLockの引数で、 ReleaseHealLock( from )の形で実行されます。objectとして渡されるので必ず型を変換しなければなりません。

private static void ReleaseHealLock( object state )

ここではstaticですが、別にstaticで無くても構いません。その場合は new TimerStateCallback( インスタンス.メソッド )の形で使用してください。

((Mobile)state).EndAction( typeof( BaseHealPotion ) );

objectのstateをMobile型に変換し、EndAction以下略です。EndActionの詳細はTips18

一定時間毎に実行

今度は一定時間毎に実行する使い方です。

public static Timer DelayCall( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback callback, object state )

基本的に時間差と使い方は一緒です。

interval
callbackを実行する間隔です。
count
繰り返す回数です。0だと終了しない限り繰り返します。 delayの時間が経過した後,intervalの間隔でcallbackが繰り返されます。