Having an event occur every n milliseconds ?

edited August 2015 in How To...

I would like a function to run every n milliseconds, regardless of what else is going on in the program. Similar to an interrupt driven function in Arduino language. Is there any way to do that in processing?

Thanks,

Mike

Answers

  • edited February 2015

    Using "official" Processing API only we can't. But w/ Java bundled libraries, sure! :-bd
    http://docs.Oracle.com/javase/8/docs/api/java/util/TimerTask.html

    /** 
     * TimerTask (v1.3)
     * by GoToLoop (2013/Dec)
     * 
     * forum.Processing.org/two/discussion/1725/millis-and-timer
     * docs.Oracle.com/javase/8/docs/api/java/util/TimerTask.html
     */
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    final Timer t = new Timer();
    boolean hasFinished = true;
    
    void draw() {
      if (hasFinished) {
        final float waitTime = random(10);
        createScheduleTimer(waitTime);
        println("\n\nTimer scheduled for " + nf(waitTime, 0, 2) + " secs.\n");
      }
    
      if ((frameCount & 0xF) == 0)   print('.');
    }
    
    void createScheduleTimer(final float sec) {
      hasFinished = false;
    
      t.schedule(new TimerTask() {
        public void run() {
          print(" " + nf(sec, 0, 2));
          hasFinished = true;
        }
      }
      , (long) (sec*1e3));
    }
    
  • edited February 2015

    A simpler approach relying on thread("") + delay() to execute a task after a specified time continually:
    http://Processing.org/reference/thread_.html

    // forum.processing.org/two/discussion/8467/a-quick-question-about-screenshots
    
    static final int FPS = 60, INTERVAL = 5 * 1000; // 5 seconds
    
    void setup() {
      size(300, 200, JAVA2D);
      frameRate(FPS);
      thread("timedShots");
    }
    
    void draw() {
      background((color) random(#000000));
    }
    
    void timedShots() {
      for (;; delay(INTERVAL))  saveFrame(dataPath("####.jpg"));
    }
    
Sign In or Register to comment.