Sometimes you want something to update in MATLAB on a regular schedule. Timer objects can do that for you. We first introduced this for test and measurement applications, but it has since been moved into base MATLAB.
In this simple example, we will create a timer object and have it fire a callback every second to output a random number to the command line.
There are a lot more useful things to do with timer objects, of course. What have you done with them? [Comment here]
As one gets to more esoteric bits, try…catch doesn’t always work. For example, some things fail by popping up a dialog for the user to asknowledge rather than Matlab’s error command.
So when I want error trapping for something that won’t run interactively, I guess how long it should take and use a timer to exit out if it takes too long.
This way if I queue 10 things up for the evening and number 3 stalls waiting for user input, it eventually gets killed and the other 9 finish.
Hello Doug,
I love your blog and I find it extremely useful.
I have a question.
Is it possible to run a timer object in the background and saving data in the background as well?
for example I was thinking to save some live data to create a time series from the Yahoo finance while running some other codes on the same time.
Thanks,
Tal
That is exactly the kind of thing timers were first introduced for. Rather than pulling data from a datafeed on the web, they were pulling data from instruments and DAQ boards.
Timers have since been put into the core of MATLAB. You can use them to run any function you want.
Doug,
I discovered timer objects about a month ago as I was looking for a way to automatically query a piece of hardware using UDP. In my application, a timer is used to regularly request system status and parse the reply. It did the trick nicely.
Once again I have to say this is blog is great. I would like to use timers for Interrupt Requests. It would be a great way to simulate microcontrollers in Matlab, so students could see what’s going on on a GUI (since most GUI development software won’t work with real IRQ in win xp). The question is: if I create several timers, once I’m doing routine of 1 timer I would like to stop the timers, but after that I would like to resume. Are the values of the timers reset after stop(a)?
I’ve been enjoying your new “Advanced MATLAB” posts. Keep up the good work!
I’m using a couple of timers in a GUI application that seems to work pretty well. My application is that I have a set of ODEs that model a process, and a complex control algorithm. The model integrates forward one second, then passes the output to the control algorithm, then back to the model with the results from the controller. This is on a timer that lets me control the frequency with which the model executes, and if the timer has a period of 1s then it runs in real time. At a period of 0.01 it’s 100x real time, etc.
I have a second timer that reads the state of the simulation and updates the GUI with new graphs and indicators of the status of the simulation. By having two timers I can decouple running the simulation from updating the display (an expensive operation). I can also use the GUI to speed up the simulation to facilitate testing.
This is my first time using timers, but I’m pretty happy with how it’s working out. I’m not sure if there’s a better way to do it, but it gets the job done. It took me quite a bit of digging to figure out a way to make a GUI that lets me interact with a running process, so hopefully this post will inspire others. Is there a better way to allow users to interact with a running simulation that using timer objects?
Doug,
One question about the timers: What determines the workspace that the timerfunction runs in? Is it like creating an anonymous function, where the inputs to the timer function are fixed when it is created, or is there a way to allow the timer function to update its inputs? For example, suppose I want to replace the waitbar with my own one. Instead of calling the Mywaitbar function every time through my for loop, I want to create a timer inside of Mywaitbar whose timer function is to check the calling function every 0.1 seconds and retrieve the value. How would I go about setting something like that up? Do I use an evalin inside of Mywaitbar? Is it even possible?
There are stopFcnCallbacks that are run when you stop a timer. With clever use of these you should be able to accomplish what you are interested in doing. I think you are effectively trying to create a pause(timer) function.
It almost sounds to me like you would be better off using Simulink for the simulation you are running. With all of the time dependencies you are working with Simulink and its constant marching of time would probably be better.
The callback occurs a few times (I say “a few” because it
could be 1, 5 or 10034, there does not seem to be any reason
to it), and the appears to get “lost”. When I query the
timer, it claims that is is running, however it has stopped
callback execution. I do a lot of process control and have
used timers quite extensively in earlier versions of MATLAB
and have never had this problem. Any ideas?
Note: When I change the number of maximum number of computational threads to 1, the timer callback seems to behave just fine…I however need to use the multiple threads in my application.”
I want to use timer function in real time signal processing application.
Could you please tell me which documents help me to understand detail variability and different uses of timer function?
Do Timer Callbacks and Handle Graphics Object Callbacks execute in the same Event Queue (i.e. same thread)? And if so, what is the Interruptible property behavior of the Timer Callback (since that is not one of its visible properties)?
I’d like to understand, if I have a Timer Callback that takes a long time to complete, can my Handle Graphics objects be updated during that time period? I’ve been trying to figure this out through an test case, but I’m running into some trouble.
That basically answers my question, however I would like to better understand how timer callbacks and user-generated event callbacks (i.e. handle graphics object callbacks) interact.
If MATLAB is single threaded the events must be processed serially, but can a timer callback interrupt a handle graphics callback with interruptible property = ‘on’ (when it reaches one of the function calls that allow it to be interrupted such as drawnow, pause, etc …)?
Since the timer callback does not have an interruptible property, can it be interrupted by any other callback in the event queue?
You blog is a lifesaver. My question for you is, I’m trying to make a GUI with some really accurate timing for events, i.e. moving boxes at certain times, having a running clock, changing colors at certain times, etc. What I want to do is use tic;toc; to give me a running time from the start and save the toc’s return value to the GUI’s handle structure. However, when I seem to do that, it seems to destroy the Handles structue, as I get the “Reference to non-existent field” error for variables that existed just a second ago. Any ideas, or is TIMER not the way to roll?
function figure1_KeyPressFcn(hObject, eventdata, handles)
handles.Key = get(gcf, 'CurrentKey')
switch(handles.Key)
case 'f12'
tic;
accurateTimer = timer;
set(accurateTimer, 'Period', .1)
set(accurateTimer, 'TimerFcn', 'handles.elapsedTime = toc;')
start(accurateTimer)
handles.workingTime = floor(handles.elapsedTime) %%Where I get my "Reference to Nonexistent Field Error"
My first guess is that you are going to want to write an actual subfunction in the code (not defining ‘handles.elapsedTime = toc;’) When you make that subfunction, be sure to actually pas in and take handles out of the function.
i need the timer function, TimerFcn to work on the handles structure when i’m working in a gui, i’ve tried a ton of things, nothing’s worked, could you help me out?
i think its a workspace issue, but i dont know how to fix it.
If you want access to the handles structure from outside the GUI, you might want to store a copy of the data you need in the root object (handle = 0) with GETAPPDATA and SETAPPDATA. It really depends on the specifics of what you are trying to do. Without more information, I can not really make a good suggestion.
I’m trying to use a timer to exit a function that’s taking too long to execute, similar to what Bob (#1 above) says he does. However, since the timer executes in the base workspace, I haven’t been able to figure out how it can tell the function to return (preferably with an error).
As a simple example, when I run this function the message displays, but the workspace remains paused:
[] = function test()
t = timer('TimerFcn','disp(''Taking too long''); return','StartDelay',5);
start(t)
pause
Is there a way to set up the timer so that function test will terminate?
If the calculation that is taking too long is in a for loop, or anything else where you can force a check from time to time, I would have the timer SETAPPDATA in the root (handle 0) after a certain amount of time. I would then have the calculation check for that data from time to time with GETAPPDATA.
This appdata shoudl be available from any workspace.
Hello Doug, I am trying to run two processes independently in a sesion of Matlab 2009a, with the timer objects t1 and t2.
My problem is that I need to pause the process 1 only, or process 2 only.
For pausing the two processes I use the command waitforbuttonpress, but I don’t know if is possible to pause
one of them only.
Thanks in advance.
Jose.
Thanks for the excellent tutorial. I was looking to use the timer to read a text file as it is being created. I have an instrument which records the data on a text file continuously. I have created a function which reads the text file and uses the data for analysis and was looking to use timer to execute that function every 2 seconds. But i keep running into an error saying too many arguments and being a rookie at MATLAB cant figure it out. It would be great if you could help.
I have a quick question. I have a function that I would like to run every 1us. I know the “period” property of the timer object cannot be reduced below 1ms. Is there a way to get this done in MATLAB. The timing is very sensitive here because I’m trying to generate a 100 Khz clock on an I/O board and slightest jitter in the clock will cause big problems in my system.
Nice blog. Could you let me know if it is possible to set up a timer within a timer?
I have a function which is set up to run regularly (primary timer). Within that function I need Matlab to pause (secondary timer) between certain steps, so I set up a wait function as below. When I run the system, Matlab hangs. Maybe there’s a way to make Matlab pause without a timer?
function waitnow(length)
t_w = timer('StartFcn', 'disp(''waiting for refresh...'')', 'TimerFcn','disp(''waited'')','StartDelay',length);
start(t_w);
wait(t_w);
% stop(t_w);
I am not sure what it would mean to have ‘nested’ timers.
You can set the period between starts, between completion and start, and other such variants. Between these and some creativity, I think you will be able to do whatever is needed.
Is there a way set a timer around an input prompt? That is, the screen displays a input prompt and the user has to enter a value and hit enter within a certain time.
Thanks for any help or referral.
I want to read data form a daq board and an rs-232 port simultaneously. I can get data out of both these objects in Matlab, but I want them to be synchronized so that the data are correspondent. After watching this video I thought this might be doable by adding a timer. But I don’t know how to do that or even where to start especially that I’m reading the rs-232 data in continuous mode (Baud rate=9600). Another solution might be reading the rs-232 data discrete (rather than continuous) w/ small delay time (e.g. 0.1s), then synchronize it w/ daq board. But I have no clue how to implement this either. Do you have any idea how to get any of these (contnious synchronized reading or discrete synchronized reading) work?
I can not think of an easy way to do that at the commend prompt. However, if you had a dialog box come up, you could set a timer to close it, and set a default value if needed.
@Nara,
It depends on the fidelity you want. How close to simultaneous do you want. If you are trying to get to hard real time, then you will want to look into Real Time Workshop.
Thanks Doug for your response. I can wait untill the reading is complete and then collect the data, so don’t have to use the real time workshop. My problem is, let’s say data collection of a tension test where the daq board reads the displacement and RS-232 port reads the load. How to get these two collect data at the same time, e.g. at a certain displacement we know the amount of load. Do you have any suugestion for that?
I’ve used them for error catching.
As one gets to more esoteric bits, try…catch doesn’t always work. For example, some things fail by popping up a dialog for the user to asknowledge rather than Matlab’s error command.
So when I want error trapping for something that won’t run interactively, I guess how long it should take and use a timer to exit out if it takes too long.
This way if I queue 10 things up for the evening and number 3 stalls waiting for user input, it eventually gets killed and the other 9 finish.
Hello Doug,
I love your blog and I find it extremely useful.
I have a question.
Is it possible to run a timer object in the background and saving data in the background as well?
for example I was thinking to save some live data to create a time series from the Yahoo finance while running some other codes on the same time.
Thanks,
Tal
Tal,
That is exactly the kind of thing timers were first introduced for. Rather than pulling data from a datafeed on the web, they were pulling data from instruments and DAQ boards.
Timers have since been put into the core of MATLAB. You can use them to run any function you want.
Doug
Doug,
I discovered timer objects about a month ago as I was looking for a way to automatically query a piece of hardware using UDP. In my application, a timer is used to regularly request system status and parse the reply. It did the trick nicely.
Dan
Dear Doug,
Once again I have to say this is blog is great. I would like to use timers for Interrupt Requests. It would be a great way to simulate microcontrollers in Matlab, so students could see what’s going on on a GUI (since most GUI development software won’t work with real IRQ in win xp). The question is: if I create several timers, once I’m doing routine of 1 timer I would like to stop the timers, but after that I would like to resume. Are the values of the timers reset after stop(a)?
Thanks,
Julio
I’ve been enjoying your new “Advanced MATLAB” posts. Keep up the good work!
I’m using a couple of timers in a GUI application that seems to work pretty well. My application is that I have a set of ODEs that model a process, and a complex control algorithm. The model integrates forward one second, then passes the output to the control algorithm, then back to the model with the results from the controller. This is on a timer that lets me control the frequency with which the model executes, and if the timer has a period of 1s then it runs in real time. At a period of 0.01 it’s 100x real time, etc.
I have a second timer that reads the state of the simulation and updates the GUI with new graphs and indicators of the status of the simulation. By having two timers I can decouple running the simulation from updating the display (an expensive operation). I can also use the GUI to speed up the simulation to facilitate testing.
This is my first time using timers, but I’m pretty happy with how it’s working out. I’m not sure if there’s a better way to do it, but it gets the job done. It took me quite a bit of digging to figure out a way to make a GUI that lets me interact with a running process, so hopefully this post will inspire others. Is there a better way to allow users to interact with a running simulation that using timer objects?
Cheers!
Ryan
Doug,
One question about the timers: What determines the workspace that the timerfunction runs in? Is it like creating an anonymous function, where the inputs to the timer function are fixed when it is created, or is there a way to allow the timer function to update its inputs? For example, suppose I want to replace the waitbar with my own one. Instead of calling the Mywaitbar function every time through my for loop, I want to create a timer inside of Mywaitbar whose timer function is to check the calling function every 0.1 seconds and retrieve the value. How would I go about setting something like that up? Do I use an evalin inside of Mywaitbar? Is it even possible?
Thanks,
Dan
Julio,
There are stopFcnCallbacks that are run when you stop a timer. With clever use of these you should be able to accomplish what you are interested in doing. I think you are effectively trying to create a pause(timer) function.
Doug
Ryan,
It almost sounds to me like you would be better off using Simulink for the simulation you are running. With all of the time dependencies you are working with Simulink and its constant marching of time would probably be better.
Doug
Dan,
Our doc can explain this much better than I can.
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f9-39541.html#f9-42494
Doug
Doug,
I posted the following questions below in the user community, but nobody has responded…I then found this discussion…Any ideas?–>
“I am posting this to see if anybody has had similar problems
with 2007b or later (when Matlab became multithreaded)…
I execute this code in the interpretor:
>>t = timer(‘Period’, 1, ‘timerfcn’, ‘disp(”hello”)’,…
‘executionmode’, ‘fixeddelay’, ‘busymode’, ‘error’);
>>start(t);
The callback occurs a few times (I say “a few” because it
could be 1, 5 or 10034, there does not seem to be any reason
to it), and the appears to get “lost”. When I query the
timer, it claims that is is running, however it has stopped
callback execution. I do a lot of process control and have
used timers quite extensively in earlier versions of MATLAB
and have never had this problem. Any ideas?
Note: When I change the number of maximum number of computational threads to 1, the timer callback seems to behave just fine…I however need to use the multiple threads in my application.”
BJ
BJ,
I think you are best served with technical support:
http://www.mathworks.com/support
They should be able to help very quickly.
Doug
Hi Doug,
I want to use timer function in real time signal processing application.
Could you please tell me which documents help me to understand detail variability and different uses of timer function?
Thanks.
Mamun
You can just type
>>doc timer
At the MATLAB prompt.
-Doug
Hello, can you help me on how to do timer objects on matlab 6.1, thanks
Hi Doug,
Do Timer Callbacks and Handle Graphics Object Callbacks execute in the same Event Queue (i.e. same thread)? And if so, what is the Interruptible property behavior of the Timer Callback (since that is not one of its visible properties)?
I’d like to understand, if I have a Timer Callback that takes a long time to complete, can my Handle Graphics objects be updated during that time period? I’ve been trying to figure this out through an test case, but I’m running into some trouble.
- Ryan
Ryan,
MATLAB is single threaded.
If you want to update graphics, at any time you can call DRAWNOW. This will flush the graphics queue.
Does this answer the heart of your question?
-Doug
@Med,
There were no timer objects in that release of MATLAB. That is why we recommend upgrading to newer versions of MATLAB.
-Doug
Hi Doug,
That basically answers my question, however I would like to better understand how timer callbacks and user-generated event callbacks (i.e. handle graphics object callbacks) interact.
If MATLAB is single threaded the events must be processed serially, but can a timer callback interrupt a handle graphics callback with interruptible property = ‘on’ (when it reaches one of the function calls that allow it to be interrupted such as drawnow, pause, etc …)?
Since the timer callback does not have an interruptible property, can it be interrupted by any other callback in the event queue?
- Ryan
Hey Doug!
You blog is a lifesaver. My question for you is, I’m trying to make a GUI with some really accurate timing for events, i.e. moving boxes at certain times, having a running clock, changing colors at certain times, etc. What I want to do is use tic;toc; to give me a running time from the start and save the toc’s return value to the GUI’s handle structure. However, when I seem to do that, it seems to destroy the Handles structue, as I get the “Reference to non-existent field” error for variables that existed just a second ago. Any ideas, or is TIMER not the way to roll?
Bill,
My first guess is that you are going to want to write an actual subfunction in the code (not defining ‘handles.elapsedTime = toc;’) When you make that subfunction, be sure to actually pas in and take handles out of the function.
I think you are running into scoping issues.
-Doug
dear doug,
i need the timer function, TimerFcn to work on the handles structure when i’m working in a gui, i’ve tried a ton of things, nothing’s worked, could you help me out?
i think its a workspace issue, but i dont know how to fix it.
If you want access to the handles structure from outside the GUI, you might want to store a copy of the data you need in the root object (handle = 0) with GETAPPDATA and SETAPPDATA. It really depends on the specifics of what you are trying to do. Without more information, I can not really make a good suggestion.
Doug
Nice blog, Doug.
I’m trying to use a timer to exit a function that’s taking too long to execute, similar to what Bob (#1 above) says he does. However, since the timer executes in the base workspace, I haven’t been able to figure out how it can tell the function to return (preferably with an error).
As a simple example, when I run this function the message displays, but the workspace remains paused:
[] = function test() t = timer('TimerFcn','disp(''Taking too long''); return','StartDelay',5); start(t) pauseIs there a way to set up the timer so that function test will terminate?
Thanks,
Ryan
@ryan,
If the calculation that is taking too long is in a for loop, or anything else where you can force a check from time to time, I would have the timer SETAPPDATA in the root (handle 0) after a certain amount of time. I would then have the calculation check for that data from time to time with GETAPPDATA.
This appdata shoudl be available from any workspace.
-Let me know,
Doug
Hello Doug, I am trying to run two processes independently in a sesion of Matlab 2009a, with the timer objects t1 and t2.
My problem is that I need to pause the process 1 only, or process 2 only.
For pausing the two processes I use the command waitforbuttonpress, but I don’t know if is possible to pause
one of them only.
Thanks in advance.
Jose.
hi Doug
Thanks for the excellent tutorial. I was looking to use the timer to read a text file as it is being created. I have an instrument which records the data on a text file continuously. I have created a function which reads the text file and uses the data for analysis and was looking to use timer to execute that function every 2 seconds. But i keep running into an error saying too many arguments and being a rookie at MATLAB cant figure it out. It would be great if you could help.
Thanks
@Ankit,
Send in the code to http://www.mathworks.com/support
Doug
Hi all,
I have a quick question. I have a function that I would like to run every 1us. I know the “period” property of the timer object cannot be reduced below 1ms. Is there a way to get this done in MATLAB. The timing is very sensitive here because I’m trying to generate a 100 Khz clock on an I/O board and slightest jitter in the clock will cause big problems in my system.
Thanks for your help
Reza
@Reza,
It sounds like you are trying to do hard real time. You should really me looking at Real Time Workshop.
http://www.mathworks.com/products/rtw/
Doug
I had followed the instructions and displayed date on gui successfully. Thank you.
Hi Doug,
Nice blog. Could you let me know if it is possible to set up a timer within a timer?
I have a function which is set up to run regularly (primary timer). Within that function I need Matlab to pause (secondary timer) between certain steps, so I set up a wait function as below. When I run the system, Matlab hangs. Maybe there’s a way to make Matlab pause without a timer?
function waitnow(length) t_w = timer('StartFcn', 'disp(''waiting for refresh...'')', 'TimerFcn','disp(''waited'')','StartDelay',length); start(t_w); wait(t_w); % stop(t_w);Hey,
Further to the previous post I discovered the pause function!
Would still be interested to know if you can have nested timers though.
Thanks,
Nikhil
I am not sure what it would mean to have ‘nested’ timers.
You can set the period between starts, between completion and start, and other such variants. Between these and some creativity, I think you will be able to do whatever is needed.
Is there a way set a timer around an input prompt? That is, the screen displays a input prompt and the user has to enter a value and hit enter within a certain time.
Thanks for any help or referral.
I want to read data form a daq board and an rs-232 port simultaneously. I can get data out of both these objects in Matlab, but I want them to be synchronized so that the data are correspondent. After watching this video I thought this might be doable by adding a timer. But I don’t know how to do that or even where to start especially that I’m reading the rs-232 data in continuous mode (Baud rate=9600). Another solution might be reading the rs-232 data discrete (rather than continuous) w/ small delay time (e.g. 0.1s), then synchronize it w/ daq board. But I have no clue how to implement this either. Do you have any idea how to get any of these (contnious synchronized reading or discrete synchronized reading) work?
@Jess,
I can not think of an easy way to do that at the commend prompt. However, if you had a dialog box come up, you could set a timer to close it, and set a default value if needed.
@Nara,
It depends on the fidelity you want. How close to simultaneous do you want. If you are trying to get to hard real time, then you will want to look into Real Time Workshop.
Doug
Thanks Doug for your response. I can wait untill the reading is complete and then collect the data, so don’t have to use the real time workshop. My problem is, let’s say data collection of a tension test where the daq board reads the displacement and RS-232 port reads the load. How to get these two collect data at the same time, e.g. at a certain displacement we know the amount of load. Do you have any suugestion for that?
@Nara,
I know it is possible.
This video is about the extent of my DAQ knowledge. Try http://www.mathworks.com/support
Sorry,
Doug
Hi Doug,
I have the very same problem Ankit had (reply #27).
t3 = timer('TimerFcn', @authentic_wrapper, 'Period', 10, 'ExecutionMode', 'FixedSpacing'); start(t3);First line is OK but after start function is says “??? Error while evaluating TimerFcn for timer ‘timer-1′
Too many input arguments.”
I have the .m file of the type function with the name authentic_wrapper in the same directory. What do I do wrong? Syntax seems to be right.
Thank you.
Paul