I would recommend to avoid this at all costs.
Keep the script simple.
If this question is related to a case you have open, and you actually want to do some 'service dampening'
you should try to use existing counters instead of creating your own one.
For example if you do a 'sho service summary' you could ugrep the last column which is the number of state transitions.
You could also reconfigure the frequency on the fly.
You could also run a script with the command scheduler instead of from the service itself.
This script would monitor all the keepalives and could store variable and also reconfigure frequency on the fly.
As you can see, there are many ways to achieve what you want.
Regards,
Gilles.