How to schedule loop in Java - 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

Related

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

Printing something in Java after a certain amount of time has passed

I'm working on a text adventure game for my Java class, and I'm running into a problem while trying to time a print statement from showing up in the console.
Basically after 45 seconds I would like a print statement to show up, in this case the print statement would be reminding the user that they need to let their virtual dog out...
I also need the timer to reset after the user gives the correct command.
import java.util.Timer;
import java.util.TimerTask;
...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("delayed hello world");
}
}, 45000);
Timer
TimerTask
To cancel the timer, either use a TimerTask variable to remember the task and then call its cancel() method, or use timer.purge(); the latter cancels all tasks on the timer. To schedule the task again, just repeat.
You'll probably want to do more advanced operations in the future, so reading the Timer API docs is a good idea.
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
System.out.println(" let the virtual dog out ");
}
}, 45000);
Try running in a new Thread.
new Thread(new Runnable()
{
public void run()
{
Thread.sleep(45000);
System.out.println("My message");
}
})
.run();
This should work.
Just tell the thread to sleep for 45 seconds, there is a tutorial here:
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
Tell the main thread to sleep might not be ideal as it will cause your program to basically stop. Use a another thread(need to do a little multi-threading) for timing your output and do a check if the message should be printed after the 45s.

Scheduling a method to execute recursively and terminate that method

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.

Can you execute a task repeatedly in Java?

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.

How to set a timer but don't run repeatly

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

Categories