三个timer相关的类

来源:互联网 发布:淘宝客户关系管理标签 编辑:程序博客网 时间:2024/05/16 07:16

三个timer相关的类之一 - CIdle 收藏
class CIdle : public CActive;


Description:


- An active object that performs low-priority processing when no higher-priority active objects are ready to run. (一个低优先级的活动对象,在没有其他的高优先级的活动对象准备运行的时候才会调用这个活动对象)

 

- An idle time active object together with its associated callback function may be used to implement potentially long running background tasks, such as spreadsheet recalculation and word processor repagination.


Construction and destruction:


static IMPORT_C CIdle *NewL(TInt aPriority);

- Allocates and initialises an Idle time active object, adds it to the active scheduler, but leaves on failure.

 

protected: IMPORT_C CIdle(TInt aPriority);

- Protected constructor taking a priority value. Sets this active object's priority value.


Member functions:

 

IMPORT_C void Start(TCallBack aCallBack);

- Starts the background task.

- The background task is encapsulated in the callback. The function represented by this callback is called every time this Idle time active object is scheduled to run.(仍然有个callback的函数会被调用,CIdle实现了CActive的RunL和DoCancel,我们只需要构建一个CIdle的对象,然后调用其Start方法,实现我们的Callback函数即可。)

- The callback function should be structured to perform a background task in many increments, i.e. it should voluntarily relinquish control (i.e. return) after a suitable time interval to allow other, higher priority events to be handled. (用于处理后台任务,任务比较大,但是优先级不高)

- If the callback function has further work to do, it should return a true value. This ensures that the active object is scheduled to run again later. (如果还有事情要做就返回ETrue,如果任务都完成了就返回EFalse)

- Once the callback function has finally completed its work, it should return a false value. The active object is then no longer scheduled to run.

protected: virtual IMPORT_C void RunL();

- Handles this idle active object's request completion event. It is called when nothing of a higher priority can be scheduled.

 

Example:

// IMPLEMENTATION SPECIFIC CONSTANTS

const TInt KPeriodicTimerInterval5Sec(5000000);


class CMyClass : public CBase

{

private: // New functions

    /**

    * The call back function.

    * /param aAny A pointer to this class.

    */

    static TInt IdleCallBack(TAny* aAny);

 

    /**

    * Notice that this is a sample fuction.

    */

    void SomeFunction();

 

private:    // Member data

    /**

    * The periodic timer. Owned by CMyClass

    */

    CIdle* iIdleTimer;

};

 

CMyClass::~CMyClass()

{

    if (iIdleTimer)

    {

       // Calling Cancel without checking if the timer is active is safe

       iIdleTimer ->Cancel();

    }

    delete iIdleTimer;

}


void CMyClass::ConstructL()

{

    if (!iIdleTimer)

    {

    iIdleTimer = CIdle::NewL( CActive::EPriorityIdle );

    }

    if (iIdleTimer ->IsActive() )

    {

       iIdleTimer ->Cancel();

    }

    iIdleTimer ->Start( TCallBack(PeriodicTimerCallBack, this ) );

}


TInt CMyClass::PeriodicTimerCallBack(TAny* aAny)

{

    CMyClass* self = static_cast<CMyClass*>( aAny );

    return self->SomeFunction();

}


void CMyClass::SomeFunction()

{

    if (finished)

{

    return EFalse;

}

else

    {

       return ETrue;

}

}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jasonfqw/archive/2009/11/26/4876004.aspx

 

 

三个timer相关的类之一 - CTimer

 

 

class CTimer : public CActive;

 

Description:

- Base class for a timer active object.

- This is an active object that uses the asynchronous services provided by RTimer, to generate events. These events occur either at a specific time specified as a TTime, or after an interval specified in microseconds. (使用的两个APIAt() or After())

- The RunL() virtual member function is called by the active scheduler after this event occurs.

- To write a class derived from CTimer, first define and implement a constructor through which the priority of the CTimer active object can be specified. Then define and implement a suitable RunL() function to handle the completion of a timer request. This function is not defined by CTimer itself and must, therefore, be provided by the derived class. (派生类在其默认构造函数的初始化列表里面调用CTimer的构造函数来初始化CTimer的优先级。而且RunL()CTimer里没有做实现,所以派生类必须做实现,CTimer实现了DoCancel())

- Note that the CPeriodic and CHeartbeat classes are derived from CTimer, and answer most timing needs.

 

Construction and destruction:

 

protected: IMPORT_C CTimer(TInt aPriority);

- Classes derived from CTimer must define and provide a constructor through which the priority of the active object can be passed. Such a constructor can call CTimer's constructor in its constructor initialisation list.

 

protected: IMPORT_C void ConstructL();

- The function must be called before any timer requests (i.e. calls to RTimer::After() or RTimer::At()) can be made.

- Since it is protected, it cannot be called directly by clients of CTimer derived classes. Typically, a derived class makes a base call to this function in the second phase of two-phase construction; i.e. the derived class defines and implements its own ConstructL() function within which it makes a base call to CTimer::ConstructL().

(继续说明在派生类的默认构造函数的初始化列表里面初始化CTimer的优先级,和必须在ConstructL()里面调用CTimerConstructL())

 

Member functions:

IMPORT_C void At(const TTime &aTime);

- Requests an event at a given local time.

- Notes:

   1. The CTimer' RunL() function will be run as soon as possible after the specified system time.

   2. The RunL() may be delayed because the RunL() of another active object, with the deepest nesting-level active scheduler on the same thread, is running when the event occurs: this cannot be avoided, but can be minimised by making all RunL()s of short duration.

   3. The RunL() may be delayed because other, higher-priority, active objects are scheduled instead. This can be avoided by making CTimers very high-priority.

   4. The TTime object should be set to the home time.

IMPORT_C void After(TTimeIntervalMicroSeconds32 anInterval);

- Requests an event after an interval.

- This timer completes after the specified number of microseconds. The "after timer" counter stops during power-down. Therefore, a 5-second timer will complete late if the machine is turned off 2 seconds after the request is made.

protected: virtual IMPORT_C void DoCancel();

- Implements cancellation of an outstanding request

- This function is called as part of the active object's Cancel().

- It must call the appropriate cancel function offered by the active object's asynchronous service provider. The asynchronous service provider's cancel is expected to act immediately.

Example:

// CTimer实现一个定时器,结合Obsever模式,使其更common的使用

class MTimeOutTimer

{

public:

    virtual void TimeExpired() = 0;

};

 

class CTimeOutTimer : public CTimer

{

public:

    static CTimeOutTimer* NewL(MTimeOutTimer& aTimeOutTimer);

    static CTimeOutTimer* NewLC(MTimeOutTimer& aTimeOutTimer);

    ~CTimeOutTimer();  

protected:

    virtual void RunL();   

private:

    CTimeOutTimer(MTimeOutTimer& aTimeOutTimer);

    void ConstructL();

private:

    MTimeOutTimer& iTimer;

};

 

#include "TimeOutTimer.h"

 

CTimeOutTimer* CTimeOutTimer::NewL(MTimeOutTimer& aTimeOutTimer)

{

    CTimeOutTimer* self = CTimeOutTimer::NewLC(aTimeOutTimer);

    CleanupStack::Pop(self);

    return self;

}

 

CTimeOutTimer* CTimeOutTimer::NewLC(MTimeOutTimer& aTimeOutTimer)

{

    CTimeOutTimer* self = new (ELeave) CTimeOutTimer(aTimeOutTimer);

    CleanupStack::PushL(self);

    self->ConstructL();

    return self;

}

 

CTimeOutTimer::CTimeOutTimer(MTimeOutTimer& aTimeOutTimer)

    : CTimer(EPriorityStandard) //初始化优先级

    , iTimer(aTimeOutTimer)

{

}

 

CTimeOutTimer::~CTimeOutTimer()

{

    Cancel();

}

 

void CTimeOutTimer::ConstructL()

{

    CTimer::ConstructL(); // 调用基类的构造

    CActiveScheduler::Add(this);

}

 

void CTimeOutTimer::RunL()

{

    iTimer.TimeExpired(); // Observer模式相结合使用

}

 

三个timer相关的类之一 - CPeriodic 收藏

class CPeriodic : public CTimer;

Description:

- Periodic timer active object.

- This class generates regular timer events and handles them with a callback function. The callback is specified as a parameter to Start().(周期性的产生定时时间)

- The callback may not be called immediately after the signal from the timer request has been generated, for the following reasons:

1. the RunL() of another active object may be running at the time of the signal

2. other active objects may have a higher priority than the CPeriodic

- If timing accuracy is important to your application, you can minimise the first problem by ensuring all RunL()s complete quickly, and can eliminate the second by giving the CPeriodic a higher priority than any other active object. Although it is generally recommended that timer-related active objects have a high priority, this will not address the problem of CPeriodic timers running behind, because active object scheduling is not pre-emptive. (如果需要精确定时的话,需要提高CPeriodic优先级或是使得RunL()尽可能的短)

- After a timer signal generated by a CPeriodic, the next signal is requested just before running the callback, and this request can be delayed for the same reasons that running the callback can be delayed. Therefore, a large number N of periods may add up to somewhat more than N times the requested period time. If absolute precision is required in tracking time, do not rely on counting the number of times the callback is called: read the value of the system clock every time you need it.

 

Construction and destruction:

 

static IMPORT_C CPeriodic *NewL(TInt aPriority);

- Allocates and constructs a CPeriodic object - leaving.

- Specify a high priority so the callback function is scheduled as soon as possible after the timer events complete.

 

protected: IMPORT_C CPeriodic(TInt aPriority);

- Classes derived from CPeriodic must define and provide a constructor through which the priority of the active object can be passed. Such a constructor can call CPeriodic's constructor in its constructor initialisation list.

 

Member functions:

 

void Start(TTimeIntervalMicroSeconds32 aDelay, TTimeIntervalMicroSeconds32 anInterval, TCallBack aCallBack);

- Starts generating periodic events.

- The event calls the protected RunL() function, which in turn calls the function specified by aCallBack. The first event is generated after aDelay microseconds; subsequent events are generated regularly thereafter at intervals of anInterval microseconds.( 时间到达后,AS会调用RunL(),其又会调用这个callback函数)

- The TCallBack contains a function pointer and a TAny* pointer. The function will be repeatedly called with the pointer as a parameter.

- Once started, periodic events are generated until the CPeriodic object is destroyed.

 

protected: virtual IMPORT_C void RunL();

- Handles an active object's request completion event.

- A derived class must provide an implementation to handle the completed request. If appropriate, it may issue another request.

- The function is called by the active scheduler when a request completion event occurs, i.e. after the active scheduler's WaitForAnyRequest() function completes.

 

Example:

// IMPLEMENTATION SPECIFIC CONSTANTS

const TInt KPeriodicTimerInterval5Sec(5000000);

class CMyClass : public CBase

{

    ....

private: // New functions

    /**

    * The call back function.

    * /param aAny A pointer to this class.

    */

    static TInt PeriodicTimerCallBack(TAny* aAny);

 

    /**

    * Notice that this is a sample fuction.

    */

    void SomeFunction();

 

private:   // Member data

    /**

    * The periodic timer.

    * Owned by CMyClass

    */

    CPeriodic* iPeriodicTimer;

};

 

CMyClass::~CMyClass()

{

    if (iPeriodicTimer)

    {

       // Calling Cancel without checking if the timer is active is safe

       iPeriodicTimer->Cancel();

    }

    delete iPeriodicTimer;

}

 

void CMyClass::ConstructL()

{

    // Initialize the periodic timer.

    iPeriodicTimer = CPeriodic::NewL(CActive::EPriorityIdle);

    // Start the periodic timer, when ever the time elapsed

    // the PeriodicTimerCallBack() will get called.

    // Notice: The timer will periodically hit the PeriodicTimerCallBack

    // until you cancel the timer by calling iPeriodicTimer->Cancel().

    iPeriodicTimer->Start(KPeriodicTimerInterval5Sec, KPeriodicTimerInterval5Sec,     TCallBack(PeriodicTimerCallBack, this));

}

 

TInt CMyClass::PeriodicTimerCallBack(TAny* aAny)

{

    CMyClass* self = static_cast<CMyClass*>( aAny );

   

    // TODO: The below call is a sample function,

    // you may change it to your requirement.

    self->SomeFunction();

   

    // Cancel the timer when the callback should not be called again.

    // Call: self->iPeriodicTimer->Cancel();

   

    return KErrNone; // Return value ignored by CPeriodic

}

 

void CMyClass::SomeFunction()

{

    // TODO: Your code!

}

CPeriodic 继承了CTimer所以做了一些必要的工作,比如调用基类的默认构造函数来设置优先级,调用ASadd方法等等。