Reputation: 23025
Please have a look at the following code
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, System.currentTimeMillis(),1000);
}
public static void main(String[]args)
{
new Test();
}
}
In here, you can see it is not printing anything! In other words, the time is not scheduled! Why is that? I want to schedule the task to happen in every second. Please help!
Upvotes: 0
Views: 969
Reputation: 61148
Take a look at the javadoc, there are two methods:
schedule(TimerTask task, Date firstTime, long period)
schedule(TimerTask task, long delay, long period)
You are passing in (TimerTask, long, long)
and are therefore invoking the second one - i.e. schedule the task to run for the first time in System.currentTimeMillis()
millis and every second thereafter. So your task will run for the first time at Thu Jun 01 06:45:28 BST 2056
, to find that out:
public static void main(String[] args) {
System.out.println(new Date(2*System.currentTimeMillis()));
}
You need to invoke the method with zero:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Updated");
}
}, 0, 1000);
This means schedule the task to run for the first time in zero millis and every second thereafter.
Upvotes: 2
Reputation: 2067
You have set the delay to the current time in millis (which would be a very long time :) ). You probably intended this:
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, new Date(System.currentTimeMillis()),1000); //<--- Notice a date is being constructed
}
public static void main(String[]args)
{
new Test();
}
}
Where you set the firstTime to the current date.
Upvotes: 0
Reputation: 3554
Try to execute this code:
import java.util.Timer;
import java.util.TimerTask;
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, 0,1000);
}
public static void main(String[]args)
{
new Test();
}
}
Upvotes: 2
Reputation: 44808
You are telling the Timer
to wait (approximately) 1363531420 milliseconds before executing your TimerTask
. This works out to ~42 years. You should be using Timer.schedule(yourTask, 0, 1000)
.
Upvotes: 6