I'm trying to launch a thread that needs to execute a task every second. So what I did from now is making a loop on this code:
// execute my task
..
lastScan.setTime(lastScan.getTime() + 1000);
long timeToSleep = (lastScan.getTime() - new Date().getTime());
try {
Thread.sleep(timeToSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
This works, but I was wondering if there is something more elegant, and maybe more safe, for example a function that awake my thread when the current Date reach a given time.
Thanks in advance for your suggestions.
Try using ScheduledExecutorService :
ScheduledExecutorService es = Executors.newScheduledThreadPool(10); //number of threads
From there, the class has different methods for passing Runnable
objects for which you can run on a timed delay in a separate thread
看一下Java Timer类,这将帮助您更优雅地进行定时循环。
You can use Timer and TimerTask, This is a sample code that prints the same line every 5 seconds
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class TimeReminder {
Timer timer;
public TimeReminder(int seconds) {
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new RemindTask(), Calendar.getInstance().getTime(), seconds * 1000);
}
class RemindTask extends TimerTask {
@Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
}
}
public static void main(String args[]) {
new TimeReminder(5);
System.out.println("Timertask is scheduled with Java timer.");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.