# OpTimer

`OpTimer` is a timer class implemented in hardcore, which internally uses the `MessageHandler`. It can be used to get called back after some time. The API is found in timer/optimer.h.
The following code is describing how one could implement a class which does something at regular intervals, for example refreshing the content of a page, redrawing something, checking mail account etc.

    class Refresher : public OpTimerListener
    {
    public:
    	Refresher() : timer(NULL) {}
    	~Refresher()
    	{
    		delete timer;
    	}

    	OP_STATUS StartRefreshing(int ms, RefreshingObject* r)
    	{
    		this->ms = ms;
    		this->r = r;
    		timer = new OpTimer();
    		if (!timer)
    			return OpStatus::ERR_NO_MEMORY;
    		timer->SetTimerListener(this);
    		timer->Start(ms);
    		return OpStatus::OK;
    	}

    	void OnTimeout(OpTimer* timer)
    	{
    		r->Refresh();
    		timer->Start(1000);
    	}

    private:
    	OpTimer* timer;
    	int ms;
    	RefreshingObject* r;
    };

If the life time of the timer object is as long as the life time of the `Refresher` object one could simplify by not allocating the timer with new. This also makes the `OP_STATUS` return value for StartRefreshing unnecessary.

    class Refresher : public OpTimerListener
    {
    public:
    	void StartRefreshing(int ms, RefreshingObject* r)
    	{
    		this->ms = ms;
    		this->r = r;
    		timer.SetTimerListener(this);
    		timer.Start(ms);
    	}

    	void OnTimeout(OpTimer* timer)
    	{
    		r->Refresh();
    		timer.Start(1000);
    	}

    private:
    	OpTimer timer;
    	int ms;
    	RefreshingObject* r;
    };