Call method after X time in java - java

I am using java 8 and netty(async), i have client server application.I i want call some method after X time for each channel.
I tried java.util.TimerTask, the problem is that the run method wont get any arguments, i want to run the method with argument, how can i run method after X seconds?
I have tried:
import java.util.TimerTask;
public class MyTimer extends TimerTask {
public void run() {
//TODO: read from object
}
}

You just use Timer with schedule with delay
Timer time= new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//TODO: read from object
}
}, delay);
delay - delay in milliseconds..

Use :-
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

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

My java class Updater don't update

I would like to know where is the problem in this class, I'm making a class that every n seconds make something, but it appear to do it only 1 time.
this is the class
import java.util.Timer;
import java.util.TimerTask;
public class Updater {
private Timer timer;
public Updater(int seconds){
timer = new Timer();
timer.schedule(new UpdaterTask(), seconds*1000);
}
class UpdaterTask extends TimerTask {
public void run() {
System.out.println(Math.random());
timer.cancel();
}
}
}
and this is the test
public class TestUpdater {
public static void main(String[] args){
new Updater(1);
}
}
i think that this test have to give me a random number every second but after the first second the process terminate.
Sorry for the bad english and thanks for any suggestion
schedule(task, delay) only execute the task once. schedule(task, delay, period) execute the task repeatedly with fixed delay.
timer.schedule(new UpdaterTask(), 0, seconds * 1000)
Remove cancel()
// timer.cancel();
You need to comment out, the timer.cancel() call. This is making the timer itself stop after the first execution of its timer task.
Then for repeated execution, you should call scheduleAtFixedRate method, with delay == 0, to start the task immediately, and period == x seconds, to run it every x seconds.
class Updater {
private Timer timer;
public Updater(int seconds){
timer = new Timer();
timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000); // use scheduleAtFixedRate method
}
class UpdaterTask extends TimerTask {
public void run() {
System.out.println(Math.random());
//timer.cancel(); --> comment this line
}
}
}
When your main() thread terminates the application also terminates.
Just add Thread.sleep(10000) at the end of your code. It will then work for 10 seconds.
AND
Consult this answer for how to use the cancel method. I think you did not want to use it there.
AND
Change the scheduling type, use
timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000);

Java clock independent to all other operations

I am trying to simulate a live data stream, to test a program that is constantly filtering and computing data points. Mainly I need to make sure that it will meet timing.
Every 50 milliseconds there will be a new data point that will need to be computed on.
So I would like to create a java clock that is independent of what is currently running in the jvm or anything like that happening on the system.
So my question is two fold:
first of all, System.currentTimeMillis() will not be what I want here because it is based on when the jvm was opened, and it would happen when ever the system call gets executed.
second, how do i make a thread that will be constantly running and always trigger exactly on the 50ms mark?
There's pretty good, pre-defined mechanism (comparing to pure threading) of Timers and TimerTask:
import java.util.Timer;
import java.util.TimerTask;
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");
}
}
(took from: http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html)
This mechanism allows you to execute your code in RemindTask's run() method every 5 seconds (that value was specified in code)
Take a look at ScheduledExecutorService, more specifically the scheduleAtFixedRate() method.
It allows you to perform an operation at regular intervals.
Take a look at ScheduledExecutorService.
Here is an example:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
//New data point
}
}, 0, 50,TimeUnit.MILLISECONDS );

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.

timer uses large amount of memory

For my MIDI player, I wanted to print 10 times in a second to get an accuracy of the timing but, the program consume quite a large amount of memory, how do I fix the code?
public void tick(int seconds) {
timer = new Timer();
timer.schedule(new tickcount(), seconds * 100);
}
class tickcount extends TimerTask {
public void run() {
if(sequencer != null) {
System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);
timer = null;
tick(1);
} else {
timer.cancel();
}
}
}
I don't really see how this code could be causing any kind of large memory consumption, unless it has to do with the incredible rate at which it'll be creating new threads.
At any rate, you should use a ScheduledExecutorService... Timer is kind of outdated (though even using it, you shouldn't be creating a new Timer each time your task runs). If you want the code in your tickcount task to run once every 0.1 seconds, you could do it like this:
private final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
private Future<?> timingTask;
public void tick(long milliseconds) {
timingTask = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);
}
}, 0, milliseconds, TimeUnit.MILLISECONDS);
}
Here, the tick method will start your timer running, calling the Runnable every milliseconds ms, starting immediately. It also assigns a Future<?> to a field... this allows you to call timingTask.cancel(true) to cancel the scheduled task from running prior to setting sequencer to null.
Other than creating Timer object every time in tick() method call use a global timer object instance and reuse it

Categories