Scheduling multiple tasks using timers - java

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

Related

What is the difference between Timer and Runnable?

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.

How to remove/postDelayed runnables in Java?

Upon an event, I'd like to run a task/runnable but delay it's execution in 2 seconds.
During these 2 seconds, if the same event occurs, I'd like to remove the previous task and re-post it to run - again delayed by 2 seconds.
An example scenario would be background compilation. When a file is saved, I'm waiting 2 seconds and start compiling the class and other, depending classes. I don't want to do it all the time - especially if there are editors that save files automatically, like IntelliJ IDEA.
So, how can I remove/postDelayed runnables in Java, like Android's Handler (remove / postDelayed)?
you can use the Executors.newScheduledThreadPool in order to schedule the task,
and you can follow this post's answer :
BlockingQueue<Runnable> queue = threadPool.getQueue();
in order to get the queued runnables.
To delay any task and "restart" the delay, you can use Swing timer and if it is running, use its method restart.
I suppose you could use the ScheduledExecutor to accomplish this, by adding a mechanism to replace queued tasks with re-queued ones. You could look into the source code of ScheduledThreadPoolExecutor to give an idea, perhaps overriding the implementation of ScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit ) and figuring out to avoid the scheduling, only running the tasks once.
Cheers,

Swing timers and time consuming task

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.

check if the timer has any pending tasks?

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.

java class calling rest api after 2 - 3 minutes continously

I have one servlet class that is hitting a url exposed via rest. I have to call it continuously at a interval of 2 -3 minutes and keeping the response in a stack. I think, I have to do this with the help of thread mechanism.
What is best way to do this?
One option is use TimerTask: Timer shedule
TimerTask -- A task that can be scheduled for one-time or repeated execution by a Timer
Regards,
You could use a timer. Simply extend TimerTask and pass it to the Timer. If you want the task to start at application start up you can write a ServletContextListener to schedule the task.

Categories