Lifetime timer, how to do?

Hi guys, I would like to ask you for advice.

I would like to create a timer (counter) to track how long an entity has been in a certain state (for example on).

I need a lifetime timer, unaffected by recorder purge, no data should be lost.

Do you have any advice on a possible solution?

Thanks