java timer task schedule - java

From reading on Stack Overflow I've seen that many of you don't recommend using Timer Task. Hmmm... but I already implemented this:
I have this code:
detectionHandlerTimer.schedule(myTimerTask, 60 * 1000, 60 * 1000);
The thing is that work of myTimerTask lasts some time.
I would like this behavior:
wait 60 sec.
do task for some time (e.g. 40 - 100 sec).
task finished.
wait 60 seconds.
do task for some time (e.g. 40 - 100 sec).
But the code above behaves like this
wait 60 sec.
do task for some time (e.g. 40 - 100 sec).
task finished
do task for some time (e.g. 40 - 100 sec).
Because the time duration of task is bigger than 60, timer starts task immediately after task is finished. But I would like it to wait again.

This works. The key is to have the task itself (after it completes) schedule the next occurrence of the task.
import java.util.Timer;
import java.util.TimerTask;
public class TaskManager {
private Timer timer = new Timer();
public static void main(String[] args) {
TaskManager manager = new TaskManager();
manager.startTask();
}
public void startTask() {
timer.schedule(new PeriodicTask(), 0);
}
private class PeriodicTask extends TimerTask {
#Override
public void run() {
System.out.println(System.currentTimeMillis() + " Running");
/* replace with the actual task */
try {
Thread.sleep(15 * 1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
/* end task processing */
System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now");
timer.schedule(new PeriodicTask(), 10 * 1000);
}
}
}
Which prints:
$ javac TaskManager.java && java TaskManager
1288282514688 Running
1288282529711 Scheduling 10 seconds from now
1288282539712 Running
1288282554713 Scheduling 10 seconds from now
1288282564714 Running
Here's what it looks like if you extract the second components of the timestamps (for clarity):
$ javac TaskManager.java && java TaskManager
14 Running
29 (+15 seconds execution) Scheduling 10 seconds from now
39 (+10 seconds delay until next run) Running
54 (+15 seconds execution) Scheduling 10 seconds from now
64 (+10 seconds delay until next run) Running
Just replace the 10s with 60s.

Related

ScheduledExecutorService will execute irrespective of previous task completion status

I am using ScheduledExecutorService where at times task may run for 3 hours to complete pollMergeFiles.searchForFileAndExecute() method and some times it may take less than 2 minutes to complete.
My only question is if scheduler.scheduleAtFixedRate will end up executing every 10 minutes with a delay of 5 minutes or it will wait until previous task running to be completed and only then start new task?
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
...
PollMergeFiles pollMergeFiles = new PollMergeFiles();
final Runnable service = new Runnable() {
public void run() {
try {
if (counter <= 256) {
pollMergeFiles.searchForFileAndExecute();
} else if (counter > 256) {
logger.info(
"Shutdown the scheduler service since all counters were processed");
scheduler.shutdown();
}
} catch (Exception e) {
logger.error("Exception found", e);
}
}
};
scheduler.scheduleAtFixedRate(service, 5, 10, TimeUnit.Minutes);
You can check the Java doc https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html .
scheduleAtFixedRate(Runnable command, long initialDelay, long period,
TimeUnit unit) Creates and executes a periodic action that becomes
enabled first after the given initial delay, and subsequently with the
given period; that is executions will commence after initialDelay then
initialDelay+period, then initialDelay + 2 * period, and so on.
So scheduleAtFixedRate() won't wait for last task to finish. It will be executed at predefined interval (period field).
scheduleWithFixedDelay(Runnable command, long initialDelay, long
delay, TimeUnit unit) Creates and executes a periodic action that
becomes enabled first after the given initial delay, and subsequently
with the given delay between the termination of one execution and the
commencement of the next.
But scheduleWithFixedDelay() method can wait for a predefined time (delay field) after the last task is executed.

Java - Trying to make a timer

I'm trying to make a timer that goes from 15 minutes to 0 but my code doesn't work. Sorry if this is easy, I recently started learning.
package timer;
import java.util.Timer;
import java.util.TimerTask;
public class Timer {
int secondsLeft = 900;
int minutesLeft = secondsLeft/60;
int seconds2 = secondsLeft - minutesLeft * 60;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
secondsLeft--;
System.out.println("Time left : " + minutesLeft + ":" + seconds2 );
}
};
public void start() {
timer.scheduleAtFixedRate(task, 1000, 1000);
}
public static void main(String[] args) {
Timer timer = new Timer();
timer.start();
}
}
Your program is mostly written correctly, but you are not printing any changes. When the seconds count down, you need to convert existing total seconds to minutes and seconds.
You can do it several ways.
Method 1: Like you are doing it now, by
maintaining a total number of seconds. It requires two operators.
The division operator /
The remainder operator %
To get the minutes remaining, simply divide total seconds by 60. (totalSeconds / 60)
To get the seconds remaining in the current minute take the remainder (totalSeconds % 60)
Method 2: By maintaining separate values for minutes and seconds, where seconds is the number of seconds within the current minute.
define a int minutes field initialized to 15
define a int seconds field initialized to 0
When the timer task runs, you need to update those fields correctly. When the seconds reach 0
decrement the minutes and set the seconds to 59. Otherwise, just decrement the seconds.
When they both reach 0, you're done. So this requires some if clauses on your part.
Additional Recommendations
To retain the leading zeroes of minutes and seconds, you can use the following formatted print statement.
System.out.printf("Time left : %02d:%02d%n",minutesLeft, secondsLeft);
The %02d is the field width and the 0 means keep leading zeroes to fill out that field. To learn more about formatted printing, check out the Formatter class in the Java API.
And finally, please call you class something other than Timer. You are using a Timer class by that name already and even though it is in the same package it can be confusing.

JAVA - Executor Schedule get Time until next run

Currently using a ScheduledExecutorService to do a task every 45 minutes (for infinity).
executor.scheduleAtFixedRate(new Runnable() {
public void run() {
...
}, 10, 45 * 60, TimeUnit.SECONDS);
I was wondering if there was a proper way to know how long until the next iteration of the executor?
My un-proper way is to add a timer and resetting it every iterator of the executor but it feels very bad.

Timer won't stop when there is a Thread.sleep inside Java

Hello i have this code to display images with javafx
public void CantaCarta() throws InterruptedException {
startGame.setDisable(true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
SwingUtilities.invokeLater(() -> {
for (int x=1; x<55;x++){
Image image = new Image(getClass().getResource("imgs/"+JuegoLoto.Muestra(x-1)+".jpg").toString(), true);
cantada.setImage(image);
if (x >= 54) {
System.out.print("Termina");
timer.cancel();
} else {
System.out.print(" "+x+" ");
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
}
}
});
}
}, 0, 1000);
}
The images will displa correctly but when the image number 54 is in the screen it will be back to 1 in a loop all because of this
Thread.sleep(200);
How can i solve this? i want to delay the time beetween images
This doesn't begin to make sense.
You're scheduling a timer task to run every 1000 milliseconds.
The task has 54 internal iterations which each display an image and in all cases except the last sleep for 200ms.
Total time so far 10600 milliseconds plus however long it takes to display the images
The timer will reschedule the task after 1000ms of that: meanwhile
the task will cancel the timer on the last iteration.
So you will get:
53 images and 53 200ms sleeps
a restart of the task after about 10% of that is complete
a 54th image
the timer gets cancelled.
So you get about ten or eleven iterations of the task, mostly in parallel.
I suggest you:
schedule the task at 200ms intervals, have it display the next sequential image every time it is invok d, wrapping around to the beginning or cancelling the timer or whatever you want when it gets to the last image, and
get rid of the internal loop.

restricting execution time sample of threads in java

I want to simulate a scheduler in java. I have three threads defined. Now I want to execute Thread 1 to be take 10% time, Thread 2 to take 30% and Thread 3 to take remaining 60% of time approximately.
All the three threads are continous monitoring tasks which will never end.
i.e. If I execute the program for 100 minutes, then Thread 1 executes for 10 mins, Thread 2 for 30 mins & Thread 3 for 60 minutes.
and also whenever threads are being shifted (i.e. another threading going into running state), I should print that "Thread x executed for Y seconds"
Can any one please provide some pointers on achieving the above simulation in java.
This link should be interresting.
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MainThread
{
public static void main(String[] args)
{
int corePoolSize = 2;
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(corePoolSize);
/*
* This will execute the WorkerThread immediately
*/
stpe.execute(new WorkerThread("WorkerThread-Running-Immediately"));
/*
* This will execute the WorkerThread only once after 10 Seconds
*/
stpe.schedule(new WorkerThread("WorkerThread-Scheduled-After-10-seconds"), 10, TimeUnit.SECONDS);
/*
* This will execute the WorkerThread continuously for every 5 seconds with an initial delay of 10
* seconds for the first WorkerThread to start execution cycle. In this case, whether the first
* WorkerThread is completed or not, the second WorkerThread will start exactly after 5 seconds hence
* called schedule at fixed rate. This continues till 'n' threads are executed.
*/
stpe.scheduleAtFixedRate(new WorkerThread("WorkerThread-Running-At-Fixed-Rate"), 10, 5, TimeUnit.SECONDS);
/*
* This will execute the WorkerThread continuously with an initial delay of 10 seconds for the first
* WorkerThread to start execution cycle. Once the first thread execution completes then a delay of 5
* Seconds is introduced so that the next WorkerThread execution cycle starts. This continues till
* 'n' thread are executed. This is called schedule each thread with a fixed delay.
*/
stpe.scheduleWithFixedDelay(new WorkerThread("WorkerThread-Running-With-Fixed-Delay"), 10, 5, TimeUnit.SECONDS);
}
}
And a worker thread :
public class WorkerThread implements Runnable
{
private String threadName = null;
public WorkerThread(String threadName)
{
this.threadName = threadName;
}
public void run()
{
System.out.println(this.threadName + " started...");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(this.threadName + " ended...");
}
}

Categories