Matlab 中使用定时器的回调函数
我正在 MATLAB 中研究内容分发服务器的统计模型,并决定使用 OO 编程。这是我第一次使用 MATLAB 涉足面向对象,但我遇到了障碍。我正在尝试对服务器的下载连接进行建模,目前它只是一个 MATLAB 计时器和一个布尔值。当计时器到期时,我想将 isActive
字段从 true
设置为 false
。我觉得很简单,但后来我已经为此奋斗了一天多了。以下是迄今为止该类的代码:
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
I am working on a statistical model of a content distribution server in MATLAB and have decided to use OO programming. This is my first foray into OO with MATLAB and I have hit a snag. I am attempting to model a download connection to the server, at the moment it is just a MATLAB timer and a boolean. When the timer expires I want to set the isActive
field from true
to false
. So quite simple I feel but then I have been battling with this for more then a day now. Below is the code for the class so far:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我解决了我遇到的问题,问题出在回调处理程序的声明方式上。我不确定确切的原因,但如果有人感兴趣,这里有更好的解释,请参阅这篇博客文章 http://syncor.blogspot.com/2011/01/matlabusing-callbacks-in-classdef.html。
以下是我为获得成功操作所做的更改。首先,我将回调函数更改为回调的正确结构:
然后我在计时器中以不同的方式声明回调:
这对我有用。感谢您的帮助,这对我来说真的很重要:P。
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:
Then I declared the callback differently in the timer:
This worked for me. Thanks for the help it was really getting to me :P.
我未经尝试的猜测是,回调需要是静态类函数,并且参数列表需要包含计时器的正确参数。然后,静态类回调需要找到对象引用来设置实例
isActive
标志。findobj
可能会通过名称获取类对象实例,因为您选择使用句柄对象,但这可能会影响实时响应。只是一个猜测。祝你好运,我对真正的答案感兴趣,因为我最近一直在考虑尝试这个。
My guess without trying it, is that the callback needs to be a static class function and the argument list needs to be with the proper parameters for a timer. The static class callback would then need to locate the object reference to set the instance
isActive
flag.findobj
might get the class object instance by name since you chose to use a handle object but that could affect the real-time response.Just a guess. Good luck, I'm interested in the real answer since I had been thinking about trying this just recently.
---- TimerHandle.m ---------
用法:
---- TimerHandle.m ---------
Usage: