4

So, I set my timer:

timer.scheduleAtFixedRate(new TimerTask()
{
    @Override
    public void run()
    {
        ...
    }
}, 5, 5);

so I want to trigger this run() for testing something, not wait until it gets triggered. Is there a way?

John Smith
  • 6,129
  • 12
  • 68
  • 123

3 Answers3

1

Just create the Runnable object before (not using anonymus class) and use it to create a new Thread and then start it.

Something like this

   Runnable runnable = new Runnable() {
        @Override
        public void run() {
            /*impl*/
        }
    };

    new Thread(runnable).start();
Ioan
  • 5,152
  • 3
  • 31
  • 50
1

Use a ScheduledExecutorService:

// single thread pool - you can use any other scheduled thread pool
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        /*impl*/
    }
}, 5, 5, TimeUnit.MILLISECONDS);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 1
    As a side note:``ScheduledExecutorService`` is to be preferred over ``Timer``: http://stackoverflow.com/questions/409932/java-timer-vs-executorservice – Jean Logeart Jun 20 '14 at 14:01
1

why using executors or threads? its not enough* to run method? :)

// define task 
TimerTask = tt new TimerTask()
{
    @Override
    public void run()
    {
        ...
    }
};


// schedule 
timer.scheduleAtFixedRate(tt,int,int);

// run as any other method :) 
tt.run();

*when run is not enought? when we can't or don't want to block the current thread!

ceph3us
  • 7,326
  • 3
  • 36
  • 43