How to set a timer but don't run repeatly - java

In my case I created a object and planned to release it after 20 minutes(accuracy is not necessary). I know by using java.util.Timer I can create a timer.But I just want it run once. After that,the timer should stop and been released too.
Is there any way just like setTimeOut() in javascript?
Thanks.

int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
}
}, timeToRun);
Modify above so that you can schedule a job 20 minutes in future.

Use Timer::schedule(TimerTask, long) or look into the ScheduledThreadPoolExecutor or ScheduledExecutorService classes.

You can start a new thread and call sleep with the number of milliseconds to wait, then execute your instructions (on either thread). See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html for reference, and look at the various online thread tutorials if you need more help.

java.util.Timer has a cancel method in it:
http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29
However, as far as I know, in timer if you do not specify a period, scheduled task will run only once.

package com.stevej;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class StackOverflowMain {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable myAction = new Runnable() {
#Override
public void run() {
System.out.println("Hello (2 minutes into the future)");
}
};
executor.schedule(myAction, 2, TimeUnit.MINUTES);
}
}

Related

How to schedule loop in Java

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

How to awake a Thread every second, Java

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
Have a look at the Java Timer class, this will help you do a timed loop more elegantly.
I would go with :
ScheduledThreadPoolExecutor
Scheduled Pool
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.");
}
}

How can I use time in Java to manipulate code?

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);

TimerTask() not doing what was supposed to, only printing one time

public static void main(String[] args) {
Timer ttt = new Timer();
TimerTask test = new TimerTask() {
#Override
public void run() {
System.out.println("IN");
}
};
ttt.schedule(test, 1000);
}
This was supposed to print "IN" every second but it is only printing one time. Any tips? Thank you
What
You're using the one-shot version of schedule. Simply use the overloaded version that accepts an interval period:
ttt.schedule(test, 0, 1000);
Aside: The newer ExecutorService is preferred over java.util.Timer. Timer has only one executing thread, so long-running task can delay other tasks. An ExecutorService can operate using a thread pool. Discussed more here

Timer in Java Thread

I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens.
I assumed that when I define a task for my timer it automatically execute the ScheduledTask within time interval but it doesn't do anything at all.
What am I missing?
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
increaserTimer.schedule(increaseTemperature, 3000);
}
};
A few errors in your code snippet:
You extend the Thread class, which is not really good practice
You have a Timer within a Thread? That doesnt make sense as the a Timer runs on its own Thread.
You should rather (when/where necessary), implement a Runnable see here for a short example, however I cannot see the need for both a Thread and Timer in the snippet you gave.
Please see the below example of a working Timer which will simply increment the counter by one each time it is called (every 3seconds):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
}
}
Addendum:
I did a short example of incorporating a Thread into the mix. So now the TimerTask will merely increment counter by 1 every 3 seconds, and the Thread will display counters value sleeping for 1 seconds every time it checks counter (it will terminate itself and the timer after counter==3):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
//create thread to print counter value
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
System.out.println("Thread reading counter is: " + counter);
if (counter == 3) {
System.out.println("Counter has reached 3 now will terminate");
timer.cancel();//end the timer
break;//end this loop
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment counter
t.start();//start thread to display counter
}
}
import java.util.Timer;
import java.util.TimerTask;
public class ThreadTimer extends TimerTask{
static int counter = 0;
public static void main(String [] args) {
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(new ThreadTimer(), 30, 3000);
}
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
}
In order to do something every three seconds you should use scheduleAtFixedRate (see javadoc).
However your code really does nothing because you create a thread in which you start a timer just before the thread's run stops (there is nothing more to do). When the timer (which is a single shoot one) triggers, there is no thread to interrupt (run finished before).
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
//start a 3 seconds timer 10ms later
increaserTimer.scheduleAtFixedRate(increaseTemperature, 3000, 10);
while(true) {
//give it some time to see timer triggering
doSomethingMeaningful();
}
}
I think the method you've used has the signature schedule(TimerTask task, long delay) . So in effect you're just delaying the start time of the ONLY execution.
To schedule it to run every 3 seconds you need to go with this method schedule(TimerTask task, long delay, long period) where the third param is used to give the period interval.
You can refer the Timer class definition here to be of further help
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Timer & TimerTask are legacy
The Timer & TimerTask classes are now legacy. To run code at a certain time, or to run code repeatedly, use a scheduled executor service.
To quote the Timer class Javadoc:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
Executor framework
In modern Java, we use the Executors framework rather than directly addressing the Thread class.
Define your task as a Runnable or Callable. You can use compact lambda syntax seen below. Or you can use conventional syntax to define a class implementing the Runnable (or Callable) interface.
Ask a ScheduledExecutorService object to execute your Runnable object’s code every so often.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor() ;
Runnable task = () -> {
System.out.println( "Doing my thing at: " + Instant.now() );
};
long initialDelay = 0L ;
long period = 3L ;
TimeUnit timeUnit = TimeUnit.SECONDS ;
scheduledExecutorService.submit( task , initialDelay, period , timeUnit ) ;
…
scheduledExecutorService.shutdown() ; // Stops any more tasks from being scheduled.
scheduledExecutorService.awaitTermination() ; // Waits until all currently running tasks are done/failed/canceled.
Notice that we are not directly managing any Thread objects in the code above. Managing threads is the job of the executor service.
Tips:
Always shutdown your executor service gracefully when no longer needed, or when your app exits. Otherwise the backing thread pool may continue indefinitely like a zombie 🧟‍♂️.
Consider wrapping your task's working code in a try-catch. Any uncaught exception or error reaching the scheduled executor service results in silently halting the further scheduling of any more runs.

Categories