2017-08-03 59 views
0

我正在使用python/transitions来模拟一些临床情况,并且我想将elapsed_time作为转换的触发器。我已经进入状态后,认为基于时间的python跳转fsm

  1. ,已分别剔增加一个time_in_state变量,然后进行转换时time_in_state > some value

有没有一种特殊的惯用方式来做到这一点?

,非常感谢

回答

0

你可以增加一个计数器,每当一个事件被触发,只执行达到一定的计数器限制时的过渡:

from transitions import Machine 
import time 


class TickModel(object): 
    def __init__(self): 
     self.counter = 0 

    # called to increase the counter 
    def increase_counter(self): 
     self.counter += 1 
     print("Current state: {0}; Counter: {1}".format(self.state, self.counter)) 

    # reset the counter when the state was changed 
    def reset_counter(self): 
     self.counter = 0 

    # set the counter limit 
    def limit_reached(self): 
     return self.counter >= 10 # random chosen limit 


states = ['A', 'B'] 
# trigger -- (method) name of the event 
# prepare is ALWAYS called when an event is triggered; 
# a transition will only be executed when all callbacks mentioned in 'conditions' return True 
# after is only called when a transition has been successful 
transitions = [{'trigger': 'tick', 'source': 'A', 'dest': 'B', 
       'prepare': 'increase_counter', 'after': 'reset_counter', 
       'conditions': 'limit_reached'}] 
model = TickModel() 
machine = Machine(model, states=states, transitions=transitions, initial='A') 
# this part could be put into a thread for parallel processing 
while model.state != 'B': 
    model.tick() 
    time.sleep(0.5) 

# just to show that the state has been changed 
model.increase_counter() 

如果你有兴趣在实际的基于时间超时,你可以看看在转换0.6.0中引入的state features