Search code examples
timercapl

Create a pause-able timer in CAPL


I'd like to create a pause-able timer in CAPL to monitor a real system timer that ticks only under certain conditions and does pause if those are not met.

Since I can't find any pauseTimer() function in CAPL, how can I achieve this?


Solution

  • I was able to achieve my goal by means of a workaround. It is not possible to pause a timer object, but it can be disposed of (noting how much time elapsed) and restarted as a new object afterwards.

    Assume you have a timer that should tick if and only if a certain condition applies. Please refer to following code.

    variables
    {
        msTimer PauseableTimer;
        int64 Timeout = 100000;        // 100s timer
        int64 ElapsedTime = 0;
    }
    
    on message 0x10
    {
        if( /timer doesn't tick conditions / && isTimerActive(PauseableTimer))
        {
            ElapsedTime = Timeout - timeToElapse(PauseableTimer);
            cancelTimer(PauseableTimer);
        }
    
        if( /timer ticks condition/ && !isTimerActive(PauseableTimer))
        {
            setTimer(PauseableTimer, Timeout - ElapsedTime);
        }
    }
    

    One could put in some more checks, for instance I added Reset conditions on ElapsedTime to restart the clock from full duration, but overall this is a workable way to implement countdown timers that can be paused when conditions are not met.

    Any improvement is well accepted.