View Single Post
  #4   Spotlight this post!  
Unread 26-01-2012, 23:25
Lalaland1125 Lalaland1125 is offline
Registered User
AKA: Ethan Steinberg
FRC #2429
Team Role: Programmer
 
Join Date: Jan 2012
Rookie Year: 2011
Location: La Canada
Posts: 29
Lalaland1125 is an unknown quantity at this point
Re: A good time based way to program

How about you create a priority queue of sorts?

(Note that the following is a fake priority queue, it is O(n), while a sorted queue should have a much lower runtime cost)

Code:
class TimerQueue
{

   static class Pair
   {
        Runnable runnable;
        long timeWhenToRunTask;
    }

   Vector<Pair> myTasks;
   
   public void schedule(Runnable task, long timeTillTask)
   {
       myTasks.addElement( new Pair(task,timeTillTask + System.currentTimeInMillisecs() ));
   }

   public void update()
   {
        for (int i = 0; i < myTasks.size(); i++)
        {
            Pair p = myTasks.get(i);
            if (p.timeWhenToRunTask < System.currentTimeInMillisecs() )
            {   
                p.task.run();
                myTasks.remove(i); 
                i--;
            }
        }
   }
}
Warning: Unstested code, use at own risk

Then you could simply schedule tasks and they will run after the certain time has passed, assuming you call update every "tick".

I know threading can do the same things, but I do not trust neither myself nor the cRIO with threading.

Last edited by Lalaland1125 : 26-01-2012 at 23:42.
Reply With Quote