pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.49k stars 524 forks source link

reset timeout value #489

Closed jugge83 closed 3 years ago

jugge83 commented 3 years ago

Is there any way to change the state timeout value or is it immutable after machine creation?

aleneum commented 3 years ago

Hello @jugge83,

Is there any way to change the state timeout value or is it immutable after machine creation?

a state derived from Timeout has a property 'state.timeout' which can be adjusted after state creation. Every time a Timeout state is entered, the property will be evaluated. Changes to state.timeout will not be considered during an already running timeout:

from transitions import Machine
from transitions.extensions.states import Timeout, add_state_features
import time

@add_state_features(Timeout)
class TimeoutMachine(Machine):
    pass

states = ['A', {'name': 'B', 'timeout': 1.0, 'on_timeout': 'to_A'}]

m = TimeoutMachine(states=states, initial='A')
state_B = m.get_state('B')
assert state_B.timeout == 1.0
m.to_B()
# change timeout AFTER enter has no effect for the current timeout ...
state_B.timeout = 0.5
time.sleep(0.51)
assert m.is_B()
time.sleep(0.51)
assert m.is_A()
# ... but will be considered the next time the state is entered
m.to_B()
time.sleep(0.51)
assert m.is_A()