I have a method which will be called repeatedly after successive intervals.
I have used public void schedule(TimerTask task, Date firstTime, long period).
How to stop this schedule method being called after certain time.
Right now i have no idea how to stop this method.
Any help would be greatly appreciated.
You could schedule the cancellation. For example, with a ScheduledExecutor, it could look like this:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
Runnable yourRecurrentTask = ...; //your recurrent task
//run every seconds
final ScheduledFuture<?> future = scheduler.
scheduleAtFixedRate(yourRecurrentTask, 0, 1, TimeUnit.SECONDS);
Runnable cancelTask = new Runnable() {
#Override
public void run() {
future.cancel(true);
}
};
//cancel the reccurent task in 15 seconds
scheduler.schedule(cancelTask, 15, TimeUnit.SECONDS);
Can't you just stop the timer after the given time? You can use another timer, which will fire only once and will stop the other timer.
Schedule another task that hold a reference to your existing TimerTask and calls cancel on it. You should schedule this task as a one-time schedule with no repetition.
Related
I have a Timer object created as such:
Timer timer = new Timer()
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
doSomething();
}
});
timer.schedule(timerTask, 0, 10 * 1000);
This is a timer that will run every 10 seconds. What happens when the time needed to finish running doSomething() is bigger than the interval? Will the timer wait for run() to finish before starting the interval again?
From the JavaDocs
each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well
Without more details, I would suggest having a look at Timer#scheduleAtFixedRate
I want to execute method to run every five minutes and want to release the resources. Can anybody explain how to schedule a loop so that I can execute loop every five minutes or so.
Thanks,
You can try like this:
Timer timer = new Timer ();
TimerTask sometask = new TimerTask () {
#Override
public void run () {
// code
}
};
timer.schedule (sometask, 0l, 1000*60*5);
You can use TimerTask, and Timer to make schedule task, read about these helper-link-1, helper-link-2
I want to create a thread which never halts. Every second it will acquire the system time and display this on the console. This is what I have so far:
public class Test implements Runnable {
#Override
public void run() {
System.out.println(System.currentTimeMillis());
}
}
I'd like to avoid using a loop.
Using while(true) and TimeUnit.SECONDS.sleep is a possibility, but it is bad practice (as you can see from the sheer number of downvotes on this post). This SO answer gives some reasons as to why:
low level, subject to spurious wakeups
clock drift
control
intent of code
there are others.
The basic way to achieve this is to use a java.util.Timer, not to be confused with a javax.swing.Timer:
final Timer timer = new Timer("MyTimer");
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(System.currentTimeMillis());
}
}, 0, TimeUnit.SECONDS.toMillis(1));
You need to call timer.cancel() to stop the timer - as the timer is running a non-daemon thread your program will not exit until that is done.
A more advanced way, which allows multiple tasks to be scheduled to run at different intervals on a pool of the ScheduledExecutorService. This allows you to scheduleAtFixedRate which runs a task every second (regardless of how long it takes to run, i.e. the gap between start times is always the same) or scheduleWithFixedDelay which runs a task at one second intervals (i.e. the gap between the end of one run and the start of the next is always the same).
For example:
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
final ScheduledFuture<?> handle = executorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
System.out.println(System.currentTimeMillis());
}
}, 0, 1, TimeUnit.SECONDS);
To cancel the particular task you would call handle.cancel(false) (as interrupting has no effect) and to stop the executorService you would call executorService.shutdown() after which you might want to add a executorService.awaitTermination(1, TimeUnit.DAYS) to wait for all the tasks to finish.
EDIT
A comment This can be done more concisely in java 8 with lambda right? (not an expert at lambdas)
The first example, no. A Timer takes a TimerTask, this is an abstract class and not an #FunctionalInterface so a lambda is not possible. In the second case, sure:
final ScheduledFuture<?> handle = executorService.
scheduleAtFixedRate(() -> System.out.println(System.currentTimeMillis()), 0, 1, TimeUnit.SECONDS);
I'm trying to test the use of time in Java to manipulate code. So let's say I have a app with an egg. The egg won't hatch until 60 seconds have passed in the application, what method or class would I use to do this?
The Timer class should do what you are after:
A facility for threads to schedule tasks for future execution in a background thread. Tasks
may be scheduled for one-time execution, or for repeated execution at
regular intervals.
You can take a look at a simple example available here.
You can use timer in a way like this
Timer timer = new Timer();
If you want your code to run multiple times:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your logic here
// Your logic will run every 60 second
System.out.println("egg hatched");
}
}, 0, 60000);
If you want it to run only one time
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here
System.out.println("egg hatched");
}
}, 60000);
You can read more about class timer in java here
The easiest old-fashioned single thread approach is
Thread.sleep(60*1000);
System.out.println("egg hatched");
And there is no guaranty that it print exactly after minute
System.currentTimeMillis() returns the current time of the system in milliseconds to your. So you need to create a Thread checking for the current time in a while loop an react to it.
Try run it it a separate scheduled thread;
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
Runnable hatcher = new Runnable() {
#Override
public void run() {
egg.hatch();
}
};
scheduler.schedule(hatcher, 60, TimeUnit.SECONDS);
Is it possible to repeatedly execute a task each day, each minute, each second, each year? I want it to run like a daemon.
I need a scheduled task to search the database continuously; if it finds a certain value then it should execute a further task.
I want to ask whether it is possible to repeatedly
You can use a loop, or a ScheduleExecutorService, or a Timer, or Quartz.
each day each minute each second each year
So once a second.
I want it to run like a daemon.
I would just make it a daemon thread then. No need to make it "like" a daemon.
if it find the correct value then it should do the remaining task.
Simple enough.
Read the data, check the value and if its what you want do the rest.
The java.util.Timer and java.util.TimerTask classes, which I’ll refer to collectively as the Java timer framework, make it easy for programmers to schedule simple tasks.
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(5);
System.out.format("Task scheduled.%n");
}
}
OR
Scheduling a Timer Task to Run Repeatedly
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Task here ...
}
}, delay, period);
In order to do tasks based on time you would want to use threads. Check out this link in order to learn more about them: http://docs.oracle.com/javase/tutorial/essential/concurrency/threads.html
Hmm so the program is going to be running all the time? Might want to look into Java Timer
Perhaps a look at the java.util.Timer or Quartz Scheduler would be helpful.
A ScheduledThreadPoolExecutor might also be helpful. Look into their example code and you should be able to do it.