File Exchange Pick of the Week

May 5th, 2008

Advanced MATLAB: Timer objects

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]


Video Content

iconFiles.jpgiconPod.jpg

33 Responses to “Advanced MATLAB: Timer objects”

  1. Bob replied on :

    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.

  2. Tal replied on :

    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

  3. Administrator replied on :

    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

  4. Dan replied on :

    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

  5. Julio Leon replied on :

    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

  6. Ryan replied on :

    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

  7. DanK replied on :

    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

  8. Doug replied on :

    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

  9. Doug replied on :

    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

  10. Doug replied on :

    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

  11. BJ replied on :

    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

  12. Doug replied on :

    BJ,

    I think you are best served with technical support:

    http://www.mathworks.com/support

    They should be able to help very quickly.

    Doug

  13. Ozzy replied on :

    Hi,

    I am confused about TimerFcn. I am trying to GUI that can refresh data every second but i didn’t understand how to implement subroutine when timerFcn execute. Where and how i should write that?

    thanks

  14. Doug replied on :

    @Ozzy,

    There are not enough details here for me to help you. Please contact me with more specific questions, and an example of code you have tried.

    -Thanks,
    Doug

  15. Dennis Olly replied on :

    Hi Doug,

    Like your blog! Reading this post I figured it should be possible to use a timer to monitor the size of file (with the purpose of updating a progress bar).

    And indeed it works fine, except…

    When I am monitoring a file that is being retrieved through ‘mget’ (== java ‘retrieveFile’).

    It seems the java call halts all matlab timers… Can that be true?

    Thanks,
    Dennis

  16. Doug replied on :

    Dennis,

    I did not know anything about this, so I sent it to Tech Support (www.mathworks.com/support)

    Java does not halt MATLAB timers. Is there a reproducible example where this behavior does occur?

    Doug

  17. Dennis Olly replied on :

    I sent an .m file with example to your.name at mathworks.com
    Dennis

  18. Doug replied on :

    Dennis,

    Please see http://www.mathworks.com/support for further help.

    Thanks,
    Doug

  19. JoseL. Vega replied on :

    Hello Doug, I am concern about how Can I pause the timer object.
    In my code, I am running two independent process, given by two timer objects t1 and t2 and I want to pause one of them.
    How I can do it?

    I know a command called “waitforbuttonpress”…but it pause all the process.

    Thanks in advance,

    Jose.

  20. Doug replied on :

    Jose,

    You can START or STOP a timer.

    Doug

  21. Eddy replied on :

    Hi Doug,

    I am using the timer object to control the frequency of running ‘TimerFcn’ in repetition, the ‘TimePeriod’ is set to be 0.01 s, however the result is not satisfied. ‘AveragePeriod’ gives around 0.05s when the ‘TimerFcn’ running for 100 times.

    Would you please tell me if timer object can do 0.01s scheduling control or not? If so, how can i achieve that accuracy of 0.01s?

    Cheers
    Mingxu

  22. Doug replied on :

    @Eddy,

    Please see http://www.mathworks.com/support

    Thanks,
    Doug

  23. Mayur replied on :

    Hey Doug,

    I liked your tutorial and I was wondering if you could provide some advice on choice of delays/timers.

    My objective:

    1) To display an image (using JFrames in Matlab) at precisely 1s intervals (i.e. display – pause for a second,repeat). When I mean precise, I would like an accuracy of a few milliseconds, as larger delays add up on repeated presentations.

    2) When said delay is being done I also want a key capture to be done. I have scripts for these as long as I’m not using pause()

    What is the most effective way to measure the time/cause delays and still capture keystrokes in this case? I’m at a loss, please advice.

    Thanks,
    M

  24. Doug replied on :

    Mayur,

    I am not sure how accurate of timing (down to ms?) you can really get in a non-real-time OS.

    Doug

  25. imgMan replied on :

    Doug,

    Great tutorial.

    I’d like to interrupt an infinite loop with a timer.

    Setting the ErrorFcn to ‘break;’, or ‘error(”Inf loop”)’ doesn’t do the trick. The error function only returns after I manually break the loop (Ctrl-C).

    I attribute this to Matlab’s single-threadedness, and that it can’t actually interrupt what I’m doing.

    You said in this tutorial that the timer runs ‘in the background’. That doesn’t seem to be the case. It only runs after what you’re doing has paused, or allowed something else to run.

    Thoughts?

  26. Doug replied on :

    If you want to break out of a “while 1″ loop, I would put a if (getappdata(0,’breakout’)); break; end inside the loop and then have your timer set that appdata in the root as appropriate to break out.

    Doug

  27. Vicky Budhiraja replied on :

    Hello,

    Can we create and use a timeseries analysis of matlab from timer object. I am calling a function (in timer) which gives me some data upon execution. I want this data to be analysed via Timeseries.

    Thank You,
    Vicky

  28. Doug replied on :

    @Vicky,

    As long as you put it in the TS object, MATLAB does not care if it came from a timer object originally.

    Doug

  29. Saeid replied on :

    Doug;

    Great tutorial.

    I was wondering if the random numbers generated could be saved in a variable so I could stop the timer if the value of the variable gets in a certain range.

    if b<0.05
    % b used to save random number as 1x1 array
    stop(a)
    end
    
  30. Doug replied on :

    @Saeid

    Sure, why not?

    Doug

  31. Saeid replied on :

    Doug;

    Are the random numbers generated using the timer, saved in variable “a”?
    I need to stop the timer when the random number being generated gets beyond 0.9. This helps me figure out how the timer works. I was wondering why the timer does not stop when random numbers go beyond 0.9?

    Thanks.
    Saeid

    clear all
    a=timer
    set(a,'executionmode','fixedRate')
    set(a,'timerfcn','disp(rand)')
    start(a)
    
    while (a&lt0.9)
      disp('Hello World!')
     end
     stop(a)
    
  32. Doug replied on :

    @Saeid,

    “a” is a handle to the timer (a way of referring to the timer) It is not a way of knowing how long the timer has been running. You will need to store the start time somewhere and see how much time has elapsed.

    Doug

  33. Saeid replied on :

    Thanks.
    Saeid

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Brett & Jiro share their favorite user-contributed submissions from the File Exchange.

These postings are the author's and don't necessarily represent the opinions of The MathWorks.