问题
Here my code,
static ScheduledExecutorService scheduler = null;
scheduler.scheduleAtFixedRate(new Testing(),60, 24*60*60,TimeUnit.SECONDS);
public static Runnable Testing()
{ System.out.println("Testing...");
}
I want to call Runnable() method after 60 seconds later, but it call this method immediatly when i run the code. Is there any problem in my code. I'm new for scheduleAtFixedRate method. Thanks :)
回答1:
Please try this
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Testing...");
}
}, 60, 24*60*60,TimeUnit.SECONDS);
回答2:
Create a class that extends Runnable.
static class MyRunnable implements Runnable {
public void run() {
System.out.println(i + " : Testing ... Current timestamp: " + new Date());
// Put any relevant code here.
}
}
Then your code works as expected. Try running the full working code here at codiva.io online compiler ide.
A related suggestion, in professional code, people generally avoid using thread scheduler to run a task that runs daily. The most common option is to use cron job and a bit more setup. But that is out side the scope of this question.
回答3:
The Runnable is an interface and you must implement the run() method. You could try to change your code to
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Testing...");
}
},60, 24*60*60,TimeUnit.SECONDS);
来源:https://stackoverflow.com/questions/38431262/in-my-scheduleatfixedrate-method-i-put-delay-time-to-start-run-the-method-but