I would like to know what exactly the difference is between these two classes, and when should I use each.
I am asking this because I am wondering about this sample code:
mStatusChecker = new Runnable() {
#Override
public void run() {
invalidate();
mHandler.postDelayed(mStatuschecker, (long) increment * 1000);
}
};
If I put the mHandler.postDelayed line of code before invalidate(), the Runnable is executed at almost double the speed. I am wondering if a Timer could be used instead to fix this problem.
Timer is 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.
It's better to user Timer functionality if you need timer functionality like task needing to be run at regular intervals.
Java java.util.Timer is a utility class that can be used to schedule a
thread to be executed at certain time in future. Java Timer class can
be used to schedule a task to be run one-time or to be run at regular
intervals. Java Timer class is thread safe and multiple threads can
share a single Timer object without need for external synchronization.
https://www.journaldev.com/1050/java-timer-timertask-example
Timer is not an Android class, it's a Java SDK class included in the Android SDK for compatibility with legacy code. It does not play well with the Android component lifecycle and requires extra code to interact with the UI. In short, do not use Timer on Android.
Related
I´m developing a Swing application. I need to run some tasks in background that, as a result, need to display messages on the TrayIcon. Those tasks must execute repeatedly, after some fixed delay, so i research and found Swing Timers as a good option. However, at the same time those tasks can be time consuming, and i don´t want that the GUI freezes or something like that (so, in order to fullfill this last requiriment i should go with Worker Threads instead). The thing is that worker threads don´t allow me to execute this tasks with some fixed delay and "forever".
I don´t know how to solve this, so any help would be appreciated :)
Have the actionPerformed of the Timer create a SwingWorker for the actual work.
you needn't create any extra multithreading support. timers create a new thread for running the commands in actionPerformed. alternatively you may also use 'java.util.Timer' as your timer. it is easier than swing and it also creates automatic threads each time you run.
import java.util.*;
after this you may add
Timer t=new Timer();
t.scheduleAtFixedRate(new TimerTask(){
void run(){
// your codes to perform
}, /*time in miliseconds*/);
this may solve your problem
You can create your task queue.
Create a Timer, that will shedule your task to some executor. (like ThreadPoolExecutor). At any delay, periodically, an so on.
Register a listener to task completion.
Executor will work with task on background.
When task is ready, notify main application via callback.
Do not work with simple threads. Java has a lot of concurent machanics, like Future and Executors.
I am reading about timers in Java SDK 1.3
It is mentioned as follows in POSA volume 2 in active object pattern
JDK 1.3 introduced a mechansim for executing timer-based tasks
concurrently in the classes java.util.Timer and java.util.TimerTask.
When ever the scheduled execution time of a task occurs it is
executed. The scheduling calls are executed in the clinets thread,
while the tasks themselves are executed in a thread owned by Timer
object. A timer internal task queue is protected by locks because the
two threads outlined above operate on it concurrently.
The task queue is implemented as a priority queue so that the next
TimerTask to expire can be identified efficiently. The timer thread
simply waits until this expiration.
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");
}
}
My question is
Can we have multiple schedule functions with single timer? Request to give an example here and how it works. For example if we have two scheduled one task for every 5 seconds as shown above and another for every 12 seconds but I want to use same Reminder object instead of using another (i.e., creating) Reminder object. I want to know how internally it works like how timer stated like 5,5,2, 3, and so on . (as I have same kind of requirement in my project which I have to do in C++ with out using boost. I am planning to use single timer rather than multiple timers.
What is delay argument here and how it is used.
schedule(TimerTask task, long delay, long period)
Thanks for your time and help.
If you don't have to use SDK 1.3, you can use Java 5.0 which introduced the ScheduledExecutorService which makes Timers redundant IMHO.
The ScheduledExecutorService has been around more than 9 years, perhaps it is time to upgrade.
BTW 1.3 was end of lifed, before Sun officially had End of Life dates. It is ancient and unless you like history lessons, I suggest you live in the present. ;)
BTW Java 5.0 and Java 6 are both end of life and Java 7 will have its end of life date announced next year.
So I would look at Java 7 or 8 if I were you, and ignore anything which is more than a few years old because there are many practices which are either bad, or out dated on the Internet and they don't get updated.
If you like learning about bad or out of date practices, the rose india web site is the finest collection I have found. ;)
For those of you need to know, I'm writing a plugin for CraftBukkit, which is a modded version of Minecraft, and I'm a beginner level java programmer. I have what I think is a really basic question.
I'm trying to implement a countdown that executes methods to send messages to players every second for 20 seconds.
Obviously, I can't simply create a loop that loops for 20 seconds, because that loop will freeze the main thread until it finishes, which is unacceptable. (There is a lot of game code executing)
What are some approaches to creating a loop that will run passively or without halting the main thread?
The only thing I can possibly think is creating a new thread to run the countdown in.
Surely there is a simpler way to do this?
So you aren't confused, the countdown isn't initialized as part of some main loop, its initialized linearly by a user command listener, but its code executes in the main loop. What I mean by that is I need to actually START a loop that checks time, because this code is only executed once.
Sorry if I'm not being clear or making sense.
I would recommend java.util.Timer if you are not using Swing for GUI/Graphics (not familiar with CraftBukkit, so that will be up to you to determine). In particular, look at forms of schedule which allow a task to be repeated at fixed intervals.
javax.swing.Timer is similar. The biggest difference (aside from the interfaces used to respond to timers being triggered) is that javax.swing.Timer utilizes the EDT (event dispatch thread) to run events. If you're using a Swing GUI, this thread is already present and running and you want to use it. If you're not using Swing or AWT, then this is extra overhead that you don't need.
You would use a java.util.concurrent.Executors.newSingleThreadScheduledExecutor() and conveniently schedule a countdown task at 1-second intervals.
Alternatively, if you task must run on the Event Dispatch Thread (the "GUI thread"), you'll be better served by javax.swing.Timer.
Try javax.swing.Timer:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
I use the Java's Timer to schedule a task to run after some interval of time.
myTimer.schedule(myTask, delayTime);
At any point in time, is it possible to check if there is any task scheduled to be run (but has not run yet)? If so, how would I do that?
If not, what is the alternative(s) to Timer do I have?
You can (and should) use ScheduledExecutorService instead of Timer.
It handles thread crashes in a robust manner and has more flexible API
You can just add a boolean field to myTask's class, which will be set true at first execute.
Keep it simple.
How can I schedule multiple tasks using java.util.Timer. I want to read multiple files using timers. I think I have to give each file a different TimerTask so that one file gets one instance of TimerTask and other file gets another, but I don't know how to do it. Please help. Thanks in advance. Here is what I'm doing:
Timer timer = new Timer();
// repeat the check every second
timer.schedule(fileWatcherTask, new Date(), 1000);
As javadoc of Timer class indicates your tasks should take very few time. In this case you can forget about time clash. If your tasks take more then 0.1 seconds run them in separate thread. I mean use Timer as a trigger that just makes task to start in separate thread.
you can also use quartz scheduler for that refer http://www.mkyong.com/java/quartz-scheduler-example/
if you want to use timer class see the example in following image
refer link for more details