Jump to content

Android - 5 second timer not working

Flanelman
Go to solution Solved by Flanelman,

Okay I've had some tea and came back and it was a mistake on my end, I was calling the method that contained the timers within the OnLocationChange method for GoogleMaps so it was calling it every second or so, so it wasn't the timer not working, it was the timer working multiple times. Can't figure out how to delete so thought I'd explain the issue and just mark it as solved.

Hey Guys, so this is kind of a simple question but one that I can't figure out what's going wrong with. I'm trying to have something happen every 5 seconds so I wanted to set up a timer/handler to do this but everything i've tried has just waited 5 seconds, then after that initial wait just does it every second and I can't figure out why. I'm sure it's something simple and I'm just tired but I would greatly appreciate some help. I'll attach below the stuff that I've tried:

 

//1
handler.postDelayed(new Runnable() {
            public void run() {
                    System.out.println("EVERY 5 SECONDS 1");
                    handler.postDelayed(this, 5000); 
                }}, 5000);

//2
new java.util.Timer().schedule(
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("EVERY 5 SECONDS 2");
                    }
                },5000);

//3
Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run(){
                        System.out.println("EVERY 5 SECONDS 3");
                    }
                });
            }
        };
        timer.schedule(timerTask, 5000, 5000);

They're all doing the same thing nothing happens for 5 seconds (which is good) and then they spam the log every second (not so good) and I can't figure out what I'm doing wrong. Thanks in advance. :)

Link to comment
Share on other sites

Link to post
Share on other sites

Okay I've had some tea and came back and it was a mistake on my end, I was calling the method that contained the timers within the OnLocationChange method for GoogleMaps so it was calling it every second or so, so it wasn't the timer not working, it was the timer working multiple times. Can't figure out how to delete so thought I'd explain the issue and just mark it as solved.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×