2011-08-04 40 views
2

我正在研究MATLAB中的內容分發服務器的統計模型,並決定使用OO編程。這是我第一次嘗試使用MATLAB進行OO,並且遇到了一些困難。我試圖建立一個到服務器的下載連接,目前它只是一個MATLAB定時器和一個布爾值。當計時器到期時,我想將isActive字段從true設置爲false。我感覺非常簡單,但是現在我一直在爲此奮戰一整天。下面是類到目前爲止的代碼:在Matlab中使用定時器的回調函數

classdef dl<handle 
     properties 
      isActive = true 
      ttl = 0 
     end 
     methods 
      function this = startTimer(this, varargin) 
       this.ttl = timer('TimerFcn', @()killConnection(this), 'StartDelay',1);  
       start(this.ttl);    
      end 
     end 

     methods (Access = private) 
      function obj = killConnection(obj, varargin) 
       obj.isActive = false; 
      end   
     end 
    end 

回答

2

我解決了我遇到的問題,問題在於回調處理程序的聲明方式。我不確定是否確切的原因,但如果有人有興趣,這裏有一個更好的解釋,請參閱此博客文章http://syncor.blogspot.com/2011/01/matlabusing-callbacks-in-classdef.html

以下是我爲成功操作所做的更改。首先,我改變了回調函數到適當的結構回調:

function killConnection(event, string_arg, this) 

然後,我在不同的定時器聲明的回調:

this.ttl = timer('TimerFcn', {@dl.killConnection, this}, 'StartDelay',1); 

這爲我工作。感謝您的幫助,真的讓我感到:P。

+0

我不明白你的代碼裏有什麼'dl',但是我玩過它並設法使它工作。感謝你的提示:'{}'(見我的答案)。順便說一句,該鏈接的解決方案只適用於靜態方法。 – Serg

1

我的猜測沒有嘗試它,是回調需要一個靜態類的功能和參數列表需要與一個計時器合適的參數。然後,靜態類回調將需要定位對象引用以設置實例isActive標誌。 findobj可能會按名稱獲取類對象實例,因爲您選擇使用句柄對象,但這可能會影響實時響應。

this.ttl = timer('TimerFcn', @dl.killConnection, 'StartDelay',1); 


methods(Static) 
     function killConnection(obj, event, string_arg) 
     ... 
     end 
end 

只是一個猜測。祝你好運,我對真正的答案感興趣,因爲我一直在考慮這個問題。

+0

我想你沒有運氣暗示了什麼。我得到一個「未定義的函數或方法'dl.killConnection',用於'timer'類型的輸入參數錯誤返回。這是我一直遇到的同樣的問題,我不能讓它識別我想用作回調函數。 – Rabid

0

---- TimerHandle.m ---------

classdef TimerHandle < handle  
    properties 
     replay_timer 
     count = 0 
    end 
    methods 
     function register_timer(obj) 
      obj.replay_timer = timer('TimerFcn', {@obj.on_timer}, 'ExecutionMode', 'fixedSpacing', ... 
       'Period', 1, 'BusyMode', 'drop', 'TasksToExecute', inf); 
     end 
     function on_timer(obj, varargin) 
      obj.count = obj.count + 1; 
      fprintf('[%d] on_timer()\n', obj.count); 
     end 
     function delete(obj) 
      delete(obj.replay_timer); 
      [email protected](); 
     end 
    end 
end 

用法:

>> th = TimerHandle; 
>> th.register_timer 
>> start(th.replay_timer) 
[1] on_timer() 
[2] on_timer() 
[3] on_timer() 
[4] on_timer() 
[5] on_timer() 
[6] on_timer() 
[7] on_timer() 
[8] on_timer() 
[9] on_timer() 
>> stop(th.replay_timer) 
>> delete(th)