2

我正在研究 MATLAB 中的内容分发服务器的统计模型,并决定使用 OO 编程。这是我第一次使用 MATLAB 涉足 OO,但遇到了障碍。我正在尝试对与服务器的下载连接进行建模,目前它只是一个 MATLAB 计时器和一个布尔值。当计时器到期时,我想将isActive字段设置truefalse。我觉得很简单,但我已经为此奋斗了一天多。到目前为止,以下是该类的代码:

    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
4

3 回答 3

2

I solved the problem I was having, the issue was in the way the callback handler was declared. Im not sure if the precise reason but there is a better explanation here if anyone is interested, see this blog post http://syncor.blogspot.com/2011/01/matlabusing-callbacks-in-classdef.html.

Here are the changes I made to get successful operation. Firstly i changed the callback function into the proper structure for the callback:

    function killConnection(event, string_arg, this)

Then I declared the callback differently in the timer:

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

This worked for me. Thanks for the help it was really getting to me :P.

于 2011-08-05T12:37:30.750 回答
1

我没有尝试的猜测是,回调需要是一个静态类函数,并且参数列表需要带有适当的计时器参数。然后静态类回调需要定位对象引用来设置实例isActive标志。findobj由于您选择使用句柄对象,因此可能会按名称获取类对象实例,但这可能会影响实时响应。

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


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

只是一个猜测。祝你好运,我对真正的答案很感兴趣,因为我最近一直在考虑尝试这个。

于 2011-08-04T22:14:41.890 回答
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);
            obj.delete@handle();
        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)
于 2012-11-11T22:16:33.450 回答