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

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

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

How to cancel a timer.schedule() invocation early

I have scheduled a method to run at a certain date in the future; however, there are certain events that may or may not happen before that date that would mean I want to run the method earlier than the specified date; how can I do this? I currently have:
Timer timer = new Timer();
TimerTask task = new TaskToRunOnExpriation();
timer.schedule(task, myCalendarObject.getTime());
I will have many of these TimerTask's running in my application, stop specific instances of them if a certain even happens?
EDIT
I will only ever want to cancel a single Timer for a given event, is there a way of managing the identities for the Timers such that I can easily find and stop it?
If you have thousands of them you should use a ScheduledExecutorService which will pool threads rather than a Timer which will use one thread per timer.
The ScheduledFutures returned by the executor service when you schedule a task also have a cancel method to cancel the underlying tasks: future.cancel(true);.
As for cancelling the right task, you could store the futures in a Map<String, Future> so you can access them by name or id for example.
In C# I would say use delegates, but that is not an option in Java. I would work off this idea:
class Timers
{
Timer timer1;
Timer timer2;
ArrayList<Timer> timerList;
public Timers()
{
// schedule the timers
}
// cancel timers related to an event
public void eventA()
{
timer1.cancel();
timer2.cancel();
}
public void eventB()
{
for(Timer t : timerList)
t.cancel();
}
}
Use this schedule method.
public void schedule(TimerTask task,Date firstTime,long period)
task--This is the task to be scheduled.
firstTime--This is the first time at which task is to be executed.
period--This is the time in milliseconds between successive task executions
I use Timer in android to update a progress bar.Here is some of my code, hoping it can help you:
Timer timer ;
#Override
protected void onCreate(Bundle savedInstanceState) {
//....
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
updateLogoBarHandler.sendEmptyMessage(0);
Log.e("SplashActivity","updating the logo progress bar...");
}}, 0, 50);
//.....
}
//here do the timer.cancel();
private Handler updateLogoBarHandler = new Handler() {
public void handleMessage(Message msg) {
if(logobarClipe.getLevel() < 10000){
logobarClipe.setLevel(logobarClipe.getLevel() + 50);
}else{
timer.cancel();
}
super.handleMessage(msg);
}
};

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

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