Mike G
Mike G

Reputation: 4959

Implementing a timer in java

My situation is, I have two concurrent threads, one that cant start a timer and the other can stop the timer. The timer works in a way such that, once it has started it will count to 5 seconds and execute a function after, it will keep doing this until the timer is stopped by the other thread. How can this be implemented in Java. This is what I have, I feel it is the wrong way of doing it:

Note that sleep is a global volatile variable that the other two threads turn on and off.

            void creatTime(final EventHandler handler)
            {
                Thread timer = new Thread()
                {
                    public void run()
                    {
                        try
                        {
                            while(true)
                            {
                                while(sleep) Thread.sleep(1000);

                                //invoke function

                            }
                        }
                        catch(IOException e)
                        {
                            System.out.println(e);
                        }
                    }
                };
                timer.start();
            }
            }

Upvotes: 2

Views: 8019

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26175

I agree with the TimerTask recommendation. In general, the more of your thread-related work you can pass on to the higher level features of java.util.concurrent etc. the better. For example, the original code does not deal with early wake-ups from sleep.

In addition, if the sleep variable remains after redesign, it needs to be marked volatile or accessed through synchronized get and set methods. There is a limited set of activities that ensure that writes done in one thread must become visible to reads done in another thread.

Upvotes: 2

Shashank Kadne
Shashank Kadne

Reputation: 8101

You can create a TimerTask and schedule it to run every 5 seconds

TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                //Invoke your function here
            }
        };

//Create a Timer and schedule it

Timer timer = new Timer();

timer.scheduleAtFixedRate(timerTask, 0, 5*1000);

//To terminate the Timer you can call its cancel method.

Upvotes: 4

Related Questions