timer.txt

来自「利用MATLAB自带的TIMER函数处理多个线程」· 文本 代码 · 共 31 行

TXT
31
字号
码:
function timertest
%例:timer实现多线程
%作者:nostalgica
%我的Blog: nostalgica.blogcn.com
t = timer('TimerFcn',{@mycallback,'Hello Matlab!'}, 'Period', 1,'stopfcn',{@stopcallback,'Stopped!'},'TaskstoExecut',10,'execution','fixedRate');
start(t);
timestart=clock;
while(1)    
    if etime(clock,timestart)>=11%主线程约11s,timer设了10s,主线程多运行一会儿。
        break;
    end
    pause(.5);%要是不pause,Timer线程抢不到啊!!
    disp(['主线程:            ' datestr(clock)]);
end
stop(t);
disp(['总共运行时间:' num2str(etime(clock,timestart))]);
    
function mycallback(obj, event,string_arg)
txt1 = 'Timer线程';
txt2 = string_arg;

event_type = event.Type;
event_time = datestr(event.Data.time);

msg = [ txt1 '(' event_type '):' event_time];
disp(msg);

function stopcallback(obj, event,string_arg)
txt2 = string_arg;
disp(txt2);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?