This is how to arrange a Java method to run for 1 second?

In my method, I want to call another method that will run in 1 second This is what I have

final Timer timer = new Timer();

timer.schedule(new TimerTask() {
    public void run() {
          MyMethod();
          Log.w("General","This has been called one second later");
        timer.cancel();
    }
},1000);

How should this be done? Is there any other way to do it because I'm on Android? Can I repeat without any questions?

Solution

Instead of a timer, I recommend using a scheduledexecutorservice

final scheduledexecutorservice exec = Executors.newScheduledThreadPool(1);

exec.schedule(new Runnable(){
    @Override
    public void run(){
        MyMethod();
    }
},1,TimeUnit.SECONDS);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>