(1) Timer 的定义
t=timer()
设置属性:
eg. set(t,'Name','your_timer_name')
当然可以一次性设置完成:
例如:
TaskTimer=timer(...
'Name','FebirdTimer',...
'TimerFcn',@ExecuteTask,...
'ErrorFcn',@ExecuteError,...
'Period',1,...
'ExecutionMode','fixedrate')
这里TimerFcn 为Timer 执行的函数,后面的‘@ExcuteTask’ 就是你定义的函数名
同样ErrorFcn 也是一样。
Period 为执行周期,ExecutionMode 为执行模式,fixedrate 为固定频率。当然前面所说的都是在这个前提之上。
(2) 关于TimerFcn 的定义
当以TimerFcn 的定义默认必须有两个参数
function ExcuteTask(obj,eventdata)
% TODO
end
其中obj 为执行该函数所对应的timer 对象,eventdata 为事件数据,一般里面为具体时间。
当需要在ExcuteTask 中传入参数的时候,那么Timer 可以这样定义:
那么这时函数定义应该为:
function ExcuteTask(obj,eventdata,var1)
% TODO
end
其他函数的定义也类似。
(3) 关于UserData
UserData 在Timer 比较有用,因为当时用上面的方法传递参数是,Matlab 只会在第一次传入参数。
所以我们可以在UserData 这个域中保存我们的数据。
例如:
t=[0]
lh=plot(t,sin(t),'-')
t=timer(...
'Name','MyTimer',...
'TimerFcn',@ExecuteTask,...
'ErrorFcn',@ExecuteError,...
'Period',1,'TasksToExecute',100,...
'ExecutionMode','fixedrate')
ud=struct('linehandle',lh,'count',0)
set(t,'UserData',ud)
start(t)
function ExecuteTask(obj,eventdata,UserData)
ud=obj.UserData
l=ud.linehandle
c=ud.count
t=get(l,'XData')
y=get(l,'YData')
t=[t c]
y=[y sin(0.1*c)]
set(ud.linehandle,'XData',t,'YData',y)
drawnow%一般放置在set命令后,用于重构刷新图形。
ud.count=ud.count+1
set(obj,'UserData',ud)
end
以上给出了一个使用Timer 画图的方法。
(4) 关于Timer 的函数
1.start()
2.stop()
3.timerfind()
eg.删除所有的timer
ts=timerfind
if length(ts)>0
stop(ts)
delete(ts)
end
通过Name 查找特定的Timer:
t=timerfind('Name','FebirdTimer')
例如:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObjecthandle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handlesstructure with handles and user data (see GUIDATA)
tb= timer('Name','ButtonTimer','StartDelay', 4,'Period', 4,'TasksToExecute', 2,...
'ExecutionMode','fixedRate')
tb.StartFcn = {'my_callback_fcn', 'My start message'}
tb.StopFcn = { @my_callback_fcn, 'My stop message'}
tb.TimerFcn = @(x,y)disp('Hello World!')
start(tb)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObjecthandle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handlesstructure with handles and user data (see GUIDATA)
tb=timerfind('Name','ButtonTimer')
if length(tb)>0
stop(tb)
delete(tb)
end
function my_callback_fcn(obj, event, string_arg)%传入参数,前两个为默认参数
%其中event.Type为回调函数类型,event.Data为回调函数数据
txt1 = ' event occurred at '
txt2 = string_arg
event_type = event.Type%get type
event_time = datestr(event.Data.time)%get timer period
msg = [event_type txt1 event_time]
disp(msg)
disp(txt2)
end
以上给出了通过GUI button 按钮来控制timer开始和终止的方法。
可以,如果需要定时,做3个函数,定时器设置函数、定时器中断函数、定时到处理函数,在定时中断函数里面调用定时到处理函数,进行定时到处理就可以了。如果需要精确延时,设置好定时器后,循环查询定时器状态就可以了。
如果在程序主循环里,有很多事务要处理,也就是很多函数要调用,那么判断全局变量决定是否调用某函数,而这些全局变量通过定时器中断函数来设置值,就可以实现简单的多任务了。